var is_flash_installed;
var _googleInterval;

function add_css(sheet)
{
  var cssNode = document.createElement('link');
  cssNode.type = 'text/css';
  cssNode.rel = 'stylesheet';
  var vid = '1';
  cssNode.href = '/css07/' + sheet + '.css?vid=' + vid;
  cssNode.media = 'screen';
  cssNode.title = sheet;
  document.getElementsByTagName("head")[0].appendChild(cssNode);
}

function add_to_dbg_info(html)
{
  html += '<br/>';
  document.getElementById('after-page-rendered-info').innerHTML += html;
}

function res(valueIfLargeResolution, valueIfSmallResolution)
{
  if (smaller_screen())
    return valueIfSmallResolution;
  return valueIfLargeResolution;
}

function smaller_screen()
{
  if (screen_width() <= 800)
    return true;
  return false;
}

function screen_width()
{
  if (screen.availWidth)
    return screen.availWidth;
  return 800;
}

String.prototype.trim = function () 
{
  return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function get_encoded_querystring()
{
  var result = window.location.href.substring((window.location.href.indexOf('?') + 1));
  return result;
}

function track_and_goto_link(a_url, a_context)
{
  var context = a_context;
  var tracker_id = string_as_id(a_url);

  //var urchin_link = '/' + context + '/url/' + tracker_id;
  var urchin_link = '/' + context;

  //urchinTracker(urchin_link);

  window.location.href = a_url;
}

function has_flash_version(flashVersion)
{
  return true;
}

function has_flash()
{
  return has_flash_version(6);
}

function displayBorderlessPopup(url, window_name, a_width, a_height) 
{
  return displayPopup(url, window_name, a_width, a_height, 'no');
}

function displayCamtasiaVideo(video_name) 
{
  if (requires_newer_flash())
    return;

  var url = "";

  if (video_name == "professional_5minute")
    url = "media/professional_5minute/";

  displayPopup(url, video_name, 1020, 700, 'no');
}


function displayPopupVideo(video_name, flash_version) 
{
  if (requires_newer_flash(flash_version))
    return;

  var url = "";

  if (video_name == "cathypratt")
    url = "media/pratt/";
  
  if (video_name == "paola")
    url = "media/paola/";
  
  if (video_name == "educator_8minute")
    url = "media/educator_8minute/";

  if (video_name == "2minutes")
    url = "media/two_minute_overview_of_autismpro/";

  displayPopup(url, video_name, 490, 360, 'no');
}

function get_top()
{
  if (top.frames)
    return top.frames;
  return top;
}

function embedTemplateFlash(divId, swfPostFix, swfWidth, swfHeight, swfBgColor, altMode)
{
  var swfFilename = 'content/end_user/' + divId;
  embedFlashPrivate(swfFilename + swfPostFix, divId, swfWidth, swfHeight, "6", swfBgColor, altMode);
}

function embedContentFlash(divId, swfQueryString, swfWidth, swfHeight, swfBgColor, altMode)
{
  var swfFilename = 'content/end_user/' + divId;
  embedFlashPrivate(swfFilename, divId, swfWidth, swfHeight, "6", swfBgColor, altMode);
}

function embedCamtasiaVideo(divId, aWidth, aHeight)
{
  var flashVars = "csConfigFile=" + divId + "_config.xml&csColor=FFFFFF&csPreloader=" + divId + "_preload.swf";
  var controllerSwf = divId + "_controller.swf";
  var swfObj = vec_swf_object(controllerSwf, divId, aWidth, aHeight, "6", "#FFFFFF");
  swfObj.addParam("flashVars", flashVars);
  swfObj.write("flashcontent_" + divId);
}

function embedVideoFlash(vidPath, divId)
{
  var swfFilename = divId;
  embedFlashPrivate(swfFilename, divId, 390, 293, "6", "#FFFFFF");
}

function processAltContentMode(contentFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor, alt_mode)
{
  if (alt_mode == "url")
  {
    var alt_url = "?mode=url";
    window.location.href = alt_url;
  }
  else
  {
    var img_url = contentFilename + ".jpg";
    document.write("<img src='" + img_url + "' border='0' usemap='#" + divId + "' width='" + swfWidth + "' height='" + swfHeight + "'>");
  }
}

function embedFlashPrivate(contentFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor, alt_mode)
{
  var b_has_flash = has_flash_version(flashVersion);

  if (b_has_flash)
  {
    var swfObj = getFlashEmbedObj(contentFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor);
    swfObj.write("flashcontent_" + divId);
  }
  else
  {
    processAltContentMode(contentFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor, alt_mode);
  }
}

function getFlashEmbedObj(contentFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor)
{
  var swfFilename = contentFilename + ".swf";

  var result = vec_swf_object(swfFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor);
  result.addParam("flashVars", get_encoded_querystring());
  //result.addParam("wmode", "transparent");

  return result;
}

// Wrapper for returning the swf object. Allows for global changes
// to how this works later.
function vec_swf_object(swfFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor)
{
  var result = new SWFObject(swfFilename, divId, swfWidth, swfHeight, flashVersion, swfBgColor);
  return result;
}

function displayPopup(targetUrl, targetWindowName, aWidth, aHeight, wantScrollbars)
{
  var sOptions;
  var aLeft;
  var aTop;
  var hasScreenDimensions = screen.availWidth;
  var scrollbars;

  if ((wantScrollbars == true) || (wantScrollbars == "yes"))
  {
    scrollbars = 'yes';
  }
  else{
    scrollbars = 'no';
  }

  if (hasScreenDimensions) 
  {
    var aMaxWidth = screen.availWidth * 0.99;
    var aMaxHeight = screen.availHeight * 0.99;

    if (aWidth >= aMaxWidth)
      aWidth = aMaxWidth;
    if (aHeight >= aMaxHeight)
      aHeight = aMaxHeight;

    aLeft = (screen.availWidth - aWidth) / 2;
    aTop = (screen.availHeight - aHeight) / 2;
  }
  else
  {
    aLeft = 0;
    aTop = 0;
  }

  sOptions = 'location=no,menubar=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable=yes,toolbar=no,directories=no';
  sOptions = sOptions + ',width=' + aWidth;
  sOptions = sOptions + ',height=' + aHeight;
  sOptions = sOptions + ',screenX=' + aLeft + ',screenY=' + aTop + ',left=' + aLeft + ',top=' + aTop;

  newWindow = window.open(targetUrl, targetWindowName, sOptions );

  if (!newWindow || newWindow.closed || typeof newWindow.closed=='undefined') 
    return false;

  return true;
}


function isInStr(input, searchFor){
    var _input = input.toLowerCase();
    var _searchFor = searchFor.toLowerCase();
    var result = (_input.indexOf(_searchFor) != -1);
    
    return result;
}

function isMissing(AParam){
  var lParam = AParam + "";
  
  if  ((lParam == "") || (lParam == " ") || (lParam == "NaN") || (lParam == "undefined") || (lParam == "null") || (AParam == null)) 
    return true;
    
  if (trimString(lParam) == "")
    return true;
    
  return false;		
}

function isDefined(AValue){
  return (! isMissing(AValue));
}

function useDefault(AValue, ADefaultValue){
  if (isMissing(AValue))
    return ADefaultValue
  else
    return AValue;
}

function fireFunction(fcn_id)
{
  var fcn = window[fcn_id];
  if (typeof fcn == 'function') 
  {
    fcn();
    return true;
  }
  return false;
}

function NowInSeconds(){
  var lNow;
  lNow = new Date();
  return Math.floor(lNow.getTime() / 1000);
}

function clearCart(){
  if (window.confirm("Are you sure you want to empty your cart ?")){
    payForm().reset();
  }
}

function getCookie(name, defaultValue) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;

    if ((!start) && (name != document.cookie.substring(0,name.length))) 
      return defaultValue;

    if (start == -1) 
      return defaultValue;

    var end = document.cookie.indexOf(";",len);
    if (end == -1) 
      end = document.cookie.length;
    
    var result;
    result = unescape(document.cookie.substring(len,end));
    result = result + '';
    if ((result == 'NULL') || (result == '') || (result == null))
      return defaultValue;

    return result;
}

function trimString(str) 
{
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}  

function supress_errors() 
{
  return true;
}

window.onerror = supress_errors;

function requires_newer_flash(flash_version)
{
  flash_version = nvl(flash_version, 6);

  if (has_flash_version(flash_version))
    return false;

  var msg = "This video requires a newer version of the free Flash player from Adobe.\nWould you like to go to Adobe's site to install this addon now?";
  var should_install_flash = window.confirm(msg);
  if (should_install_flash)
  {
    var flash_url = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
    newWindow = window.open(flash_url, "getflash");
  }

  return true;
}

function private_display_walkthrough(subdirectory_name, flash_version)
{
  displayFlashPopup('/media/walkthroughs/' + subdirectory_name + '/player.html', 'walkthrough'+subdirectory_name, 1024, 768, 7);
}

function nvl(a_value, a_default_value)
{
  if (is_missing(a_value))
    return a_default_value;
  return a_value;
}

function is_defined(a_value)
{
  return ! is_missing(a_value);
}

function is_missing(a_value)
{
  var l_value = a_value + "";

  if (l_value == "NaN")
    return true;
  if (l_value == "null")
    return true;
  if (l_value == "")
    return true;
  if (l_value == "undefined")
    return true;

  return false;
}

function display_autismpro_educator_walkthrough()
{
  private_display_walkthrough('autismpro_educator', 8);
}

function display_autismpro_professional_walkthrough()
{
  private_display_walkthrough('autismpro_professional');
}

function display_autismpro_walkthrough()
{
  private_display_walkthrough('autismpro');
}

function display_autismpro_2min_demo()
{
  if (requires_newer_flash())
    return;

  displayPopupVideo('2minutes')
}

function display_autismpro_20min_demo()
{
  displayFlashPopup('/livedemo/lib/playback.php', 'test', 1024, 768)
  //displayFlashPopup('/media/autismpro_20_minute/', 'autismpro_20_min', 980, 664, 8)
}

function displayFlashPopup(url, window_name, a_width, a_height, a_flash_version) 
{
  if (requires_newer_flash(a_flash_version))
    return false;

  return displayBorderlessPopup(url, window_name, a_width, a_height);
}

function display_sample_workshop1()
{
  displayFlashPopup('/vec/pub/workshops/beginner/course.html?time=1282830321', 'workshopbeginner', 811, 527, 8);
}

function display_sample_workshop2()
{
  displayFlashPopup('/vec/pub/workshops/advanced/course.html?time=1282830321', 'workshopadvanced', 811, 527, 8);
}

function display_educator_8min_demo()
{
  displayFlashPopup('/media/player/', 'educator', 800, 600, 8)
}

function display_professional_5min_demo()
{
  displayFlashPopup('/media/professional_5minute/', 'professional_5minute', 1004, 565, 8)
}

function showAutismPro()
{
  showFullScreenWindow("http://www.AutismPro.net/AutismPro/SignIn/SignIn.aspx");
}

function email_link(link_text,part4,part3,part2,part1)
{
  var email = part1 + part2 + "@" + part3 + '.' + part4;
  var link = '<' + 'a hr' + 'ef="mai' + 'lto:' + email + '">' + link_text + '</' + 'a>';
  document.write(link);
}

function string_as_id(a_value)
{
  var result = a_value;

  result = result.replace(/http:\/\//ig, "")
  result = result.replace(/https:\/\//ig, "")
  result = result.replace(/\\/g, '');
  result = result.replace(/\./g, '-');
  result = result.replace(/ /g, '_');
  result = result.replace(/\?/g, '__');
  result = result.replace(/\&/g, '--');
  result = result.replace(/\=/g, '-');

  return result;
}

function are_equal(a_string1, a_string2)
{
  var l_string1 = a_string1.toLowerCase();
  var l_string2 = a_string2.toLowerCase();
  var result = (l_string1 == l_string2);

  return result;
}

function is_external_url(an_url)
{
  return ! is_local_url(an_url);
}

function in_array(search_for, an_array)
{
  var l_search_for = trimString(search_for); 

  for(var i=0; i < an_array.length; i++)
  {
    item = an_array[i];
    if (are_equal(l_search_for, item))
      return true;
  }

  return false;
}

function is_production()
{
  return is_external_url(window.location.href);
}

function is_local_url(an_url)
{
  if (in_array(an_url, ["signin","sign_in","buy_home","buy_professional","thankyoupage_subscribe","signup_for_autismpro_trial"]))
    return false;

  if (in_str(an_url, 'test.autismpro.com'))
    return true;

  if (in_str(an_url, '://localhost'))
    return true;

  if (! in_str(an_url, '://'))
    return true;

  return false;
}

function in_str(a_string, a_search_for)
{
  var l_string = a_string.toLowerCase();
  var l_search_for = a_search_for.toLowerCase();
  var index = l_string.indexOf(l_search_for);

  var result = (index != -1);

  return result;
}

function showFullScreenWindow(targetUrl) 
{
    var wOpen;
    var sOptions;
    
    if (screen.availWidth) {
        sOptions = 'status=no,menubar=no,scrollbars=yes,resizable=yes,toolbar=no,directories=no';
        sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
        sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
        sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';

        newWindow = window.open( '', 'PlanMakerPopup', sOptions );
        newWindow.location = targetUrl;
        newWindow.focus();
        newWindow.moveTo( 0, 0 );
        newWindow.resizeTo( screen.availWidth, screen.availHeight );
    }
    else {
        var newWindow = window.open(targetUrl, 'PlanMakerPopup', 'resizable=yes,location=no,directories=no,menubar=no,status=no,toolbar=no,scrollbars=yes,width=780,height=580');
        newWindow.focus();
    }
    return false;
}

function redirecttoSystemCheckPage()
{
    var url = "https://www.autismpro.net/SystemCheck/SystemCheck.aspx?targetUrl=http://www.autismpro.com/signin.php";
  window.location.href = url;
}

function delayedRedirectToSystemCheckPage()
{
    setTimeout("redirecttoSystemCheckPage()", 3000);
}

function page_info()
{
  var result = {};
  result.screen = {};
  result.screen.width = screen.width;
  result.screen.height = screen.height;
  result.url = window.location.href;
  
  var data = $.toJSON(result);
  return data;
}

function set_loading_message(an_obj)
{
  var html = '<span class="loading"> <img src="/images/loading.gif" /> </span>';
  $(an_obj).html(html);
}

function get_url_delim(an_url)
{
  var delim = '?';
  if (isInStr(an_url, '?') )
    delim = '&';
  return delim;
}

function get_url(an_url, values)
{
  var ary_parms = [];
  j=0;
  for (i=0; i < values.length; i=i+2)
  {
    ary_parms[j] = values[i] + "=" + values[i+1];
    j++;
  }

  var parms = ary_parms.join('&');
  var result = an_url + get_url_delim(an_url) + parms;

  return result;
}

function unique_url(an_url)
{
  var result = get_url(an_url,["uid", NowInSeconds()]);
  return result;
}

function track_stats()
{
  window.setTimeout(function (a,b) {
      var url = unique_url("/vec/pub/stats.php");
      var data = {};
      data.json = page_info();

      $.getJSON(url, data, function(a)
      {
      });
  },5000);
}

function addGoogleTracking()
{
  var sc = document.createElement('script');
  sc.type = 'text/javascript';
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  sc.src = gaJsHost + 'google-analytics.com/ga.js';
  document.getElementsByTagName("head").item(0).appendChild(sc);
  _googleInterval = setInterval(doActivateGoogle, 1000);
}

function activateGoogle(trackingId)
{
  if (typeof _gat != 'undefined') 
  {
    clearInterval(_googleInterval);
    var pageTracker = _gat._getTracker(trackingId);
    pageTracker._initData();
    pageTracker._trackPageview();
  }
}

if (smaller_screen())
  add_css("800x600");

function vecDeferredScript(url, callback)
{
  this.addToDoc(url);
  this.readyInterval = setInterval(callback, 1000);
}

vecDeferredScript.prototype.addToDoc = function(url)
{
  var sc = document.createElement('script');
  sc.type = 'text/javascript';
  sc.src = url;
  document.getElementsByTagName("head").item(0).appendChild(sc);
}

vecDeferredScript.prototype.scriptReady = function()
{
  clearInterval(this.readyInterval);
}

function activateGoogle(trackingId)
{
  if (typeof _gat != 'undefined') 
  {
    gsScript.scriptReady();
    var pageTracker = _gat._getTracker(trackingId);
    pageTracker._initData();
    pageTracker._trackPageview();
  }
}

function addAnalytics()
{
  addLocalTracking();
  loadGoogleAnalytics();
}

function loadGoogleAnalytics()
{
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  var url = gaJsHost + 'google-analytics.com/ga.js';
  gsScript = new vecDeferredScript(url, doActivateGoogle);
}

function doActivateAddToAny()
{
  if (typeof a2a != 'undefined') 
  {
    addToAnyScript.scriptReady();
    var a2a_config = a2a_config || {};
    a2a_config.track_links = 'ga';
    addAnalytics();
  }
}

function loadDeferredScripts()
{
  var url = "http://static.addtoany.com/menu/page.js";
  addToAnyScript = new vecDeferredScript(url, doActivateAddToAny);
}


