///- GLOBAL VARIABLES
  var ajax_c = 0; // number of currently running ajax calls
  var ajax_loops = 0; // how long it waited so far
  
///- ALL PAGES
	
	/////////////////////////////////////////////////////////
  // fix z-index issues in internet explorer 
  /////////////////////////////////////////////////////////
	$(function() {
		if($.browser.msie && $.browser.version < 8){
			var zIndexNumber = 1000;
			$('div').each(function() {
				$(this).css('zIndex', zIndexNumber);
				zIndexNumber -= 10;
			});
		}
	});
	
	
  /////////////////////////////////////////////////////////
  // add submit button link
  /////////////////////////////////////////////////////////
  $(document).ready(function() {
						  
  // only apply to faq and about page
  if($("body").attr('id') == 'faq') {
						  
	  // if column is empty, don't have a bg image and put it inside the box
	  if($("#column-right > *").size() == 0) { 
	  
		  $("#column-right").css("backgroundImage","none");
		  $("#column-right").append('<div class="sidebar-submit"><a href="domain_search_ajax.php?KeepThis=true&height=265&width=500" class="thickbox" id="submit-approval-link"><img src="images/ajaxbox/sidebar_submit.png" /></a></div>');
		  
	  } else {
		  
		  // column already has content, just put it after the box
		  if($("#column-right #btm").size() != 0) { 
			  $("#column-right").after('<div class="sidebar-submit"><a href="domain_search_ajax.php?KeepThis=true&height=265&width=500" class="thickbox" id="submit-approval-link"><img src="images/ajaxbox/sidebar_submit.png" /></a></div>');
			  
		  }
		  
	  }
	  
  }
	  // now load the thickbox
	  $("body").trigger('thickboxReadytoLoad');		
  })
     
      

  /////////////////////////////////////////////////////////
  // show keyword popup if the right condition exists
  /////////////////////////////////////////////////////////
  $(document).ready(function() {
							 
	// open the popup whenever the keyword is added into the url
	var loc_ = new String(window.location);
	var url_keyword = loc_.match('#keyword:([A-Z0-9a-z_-\s+]*)?');
	
  if(url_keyword != "" && url_keyword != null) { var url_keyword = url_keyword[1]; }
	
	if(url_keyword != "" && url_keyword != null && $("#submit-approval-link.thickbox").size() > 0) {
		// trigger the popup
		var old_a = $("#submit-approval-link.thickbox").attr('href');
		var new_a = old_a + "&keyword=" + url_keyword;
		$("#submit-approval-link.thickbox").attr('href',new_a);
		$("#submit-approval-link.thickbox").trigger("click");
		
		/* 
		put domain focus on the domain if the keyword is filled in
		*has to have a delay because without a delay it will trigger an error
		*has to repeat because sometimes it will lose focus for an unknown reason			
		*/
		$("body").bind('thickboxAjaxComplete', function() {
			$("#aj-domain-search").animate({opacity: 1.0}, 100, null, function() {
		   		caretToEnd(document.getElementById('aj-domain-search'));
				$("#aj-domain-search").animate({opacity: 1.0}, 140, null, function() {
					caretToEnd(document.getElementById('aj-domain-search'));
				});				
			});
		});
	}
  });

  
///- HOMEPAGE

    /////////////////////////////////////////////////////////
    // focus on domain input
    /////////////////////////////////////////////////////////
    function domain_input_focus() {
    
      if (document.getElementById('domain-search') != undefined) {
        caretToEnd(document.getElementById('domain-search'));
      } 
    }

    //////////////////////////////////////////////////////////
    // called when used clicks on domain submit button
    //////////////////////////////////////////////////////////
    function domain_check() {
      
      // checking for the domain to be not empty 
      if (verify_input('domain','domain-search') == false) {
        alert("Please enter a domain.");
      } else {
      
      var domain = format_domain($("#domain-search").val()); 
    
        // adjusting preloader
        ContentSet('domain-loader-url',domain);
        
        // hiding inputs, showing preloader
        $('#domain-input').hide();
        $('#domain-loader').show();
        
        // checking domain, redirecting to step 2 once that is complete
        $.get('homepage_.php?action=domain_check&domain='+SafeInput(domain),
          function(data){
            GoTo('research');
        });

        // tracking the click
        if(typeof pageTracker == 'object') {
          pageTracker._trackEvent('Homepage', 'Domain Search', domain);
        } 
      }  
    }

  /////////////////////////////////////////////////////////////////
  // pop up video when user click on the trigger
  /////////////////////////////////////////////////////////////////
/*
// these functions are caught by the JavascriptView object of the player.
function sendEvent(typ,prm)
{
thisMovie("mpl").sendEvent(typ,prm);
};

// This is a javascript handler for the player and is always needed.
function thisMovie(movieName)
{
if(navigator.appName.indexOf("Microsoft") != -1)
{
return window[movieName];
}
else
{
return document[movieName];
}
};
*/


  $(document).ready(function() {
    $("#movieTrigger").bind('click',function(){
      
      _m_ga_pageview("/virtual/quicktour/play");
      /*$("#movieWrapper").show();
      sendEvent('playpause');
      */
      var movieHolder = document.createElement('div');
      var tbOverlay = document.createElement('div'); 
      var closeWindow = document.createElement('div');
      var moviePlaceholder = document.createElement('div');
      
      closeWindow.setAttribute('id','closeMoviePopup');
      closeWindow.onclick = function(){ closeMovie(); }
      tbOverlay.onclick = function (){ closeMovie(); }
      moviePlaceholder.setAttribute('id','moviePlaceholder');
      
      movieHolder.setAttribute('id','TB_window');
      movieHolder.setAttribute('class','video');
      tbOverlay.setAttribute('id','TB_overlay');
      tbOverlay.setAttribute('class','TB_overlayBG');
   
      movieHolder.appendChild(closeWindow);
      movieHolder.appendChild(moviePlaceholder);
      window.document.body.appendChild(movieHolder);
      window.document.body.appendChild(tbOverlay);
      
      //var so = new SWFObject('/vendors/jwPlayer/player.swf','mpl','640','384','9');
      var so = new SWFObject('/vendors/jwPlayer/player.swf','mpl','600','474','9');
      so.addParam('allowfullscreen','true');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      so.addVariable('autostart','true');
      so.addVariable('file','/video/quicktour/640x480@400_22.flv');
      so.addVariable('image','/images/quicktour-preview.jpg');
      so.write('moviePlaceholder');  
        
    })
            
  })
  
 

  
  
  function closeMovie(){
   /*$("#movie_wrapper").hide();*/
    
   var movieHolder =  document.getElementById('TB_window');
   var tbOverlay =  document.getElementById('TB_overlay');
   window.document.body.removeChild(tbOverlay);  
   window.document.body.removeChild(movieHolder);
    
  }
    
    
  ///////////////////////////////////////////////////
  // popup window for when the user clicks in the "Get Started" Area
  ///////////////////////////////////////////////////
  $(document).ready(function() {
    /* focus on the domain put */
    if ($("#TB_window #aj-domain-submit").size() > 0) {
          //caretToEnd($("#TB_window #aj-domain-submit")[0]);
        }
    
    /* rebind the submit bindings whenever new ajax is loaded */
    $("body").bind('thickboxAjaxComplete', function() {
    
      /* submit */
      $("#find-domain-ajax form").bind('submit', function(){
                                
        // add the action paramater
        $("#find-domain-ajax form").attr('action','/research');
        
        if(verify_input('domain','aj-domain-search') == false || verify_input('keyword','aj-domain-keyword') == false) {
          $("#error-container").html('<div class="error">Please enter a domain and keyword</div>');
          return false;
        } else {          
          var domain = format_domain($("#aj-domain-search").val()); 
          //return true;
        }
        
        
      })
    })
    
    /* cancel */
    $("#TB_window a#close_thickbox").live('click', function(){
      tb_remove();
      return false;
    })
  })
   
///- KEYWORD RESEARCH     

    ////////////////////////////////////////////////////////
    // focus on keyword input
    ////////////////////////////////////////////////////////
    function keyword_input_focus() {
    
      if (document.getElementById('keyword-search') != undefined) { 
        document.getElementById('keyword-search').focus();
      }
    
    }

    //////////////////////////////////////////////////////
    // searching keyword
    //////////////////////////////////////////////////////
    function keyword_check(keyword,domain) {
      
      if (keyword != undefined) {
        var kwd = keyword;
      } else {  
        // getting keyword inputs
        var kwd = Value('keyword-search');
        
        // if we have multiple kewords, searching only the first one
        if (kwd.indexOf(",") != -1) {
          kwd = kwd.substring(0,kwd.indexOf(","));
        }
        
      }
      
      
      // trimming whitespace
      
      // removing quotes
      kwd = ReplaceChars(kwd,'"','"');
      
      // checking for keyword being not empty
      if (kwd == "") {
        alert("Please enter a keyword.");
      } else {
      
        // modifying preloader
        ContentSet('keyword-loader-value',kwd);
        
        // hiding inputs, showing preloader
        $('#keyword-loader').show();
        $('#keyword-input').hide();
        
        
        // displaying keyword progress
        keyword_check_progress(0);
        
        if (domain != undefined) {
          var query = "action=keyword_check&keyword="+SafeInput(kwd)+"&domain="+domain;
        } else {
          var query = "action=keyword_check&keyword="+SafeInput(kwd)+"&current_domain="+Value("current_domain");
        }
              
        // checking keyword, refreshing the page
        $.get("research_.php?"+query,
         function(data){
            ajax_done("GoTo('research');");
        });        
      }
    
    }
 
    ////////////////////////////////////////////////////
    // searching for a keyword from suggestions list
    ////////////////////////////////////////////////////
    function keyword_suggestion(suggestion_id) {
      
      // re-using keyword search function
      ValueSet('keyword-search',SafeInput(Content('suggestion_'+suggestion_id)));
      keyword_check();
      
      // disabling ability to check other suggestions
      $(".add").removeClass("add").addClass("wait").attr("href", "#"); 
      
      // scrolling the page upwards
      var hscroll = (document.all ? document.scrollLeft : window.pageXOffset);
      window.scroll(hscroll,0);
      
      // tracking
      if(typeof pageTracker == 'object') {
        pageTracker._trackEvent('Research', 'Keyword Suggestion', Value('keyword-search'));
      }
    }

    ////////////////////////////////////////////////////
    // displaying keyword search progress
    ////////////////////////////////////////////////////
    function keyword_check_progress(seconds) {

      var status = "";
      
      if (seconds < 5) {
        status = "Checking current website rankings...";
      } else if (seconds < 10) {
        status = "Getting keyword data...";
      } else if (seconds < 15) {
        status = "Gathering search volume data...";
      } else if (seconds < 20) {
        status = "Calculating SEO opportunity...";
      } else if (seconds < 45) {
        status = "Calculating SEO pricing based upon rankings...";
      } else if (seconds < 120) {
        status = "Thanks for being patient, your results will be up soon...";
      } else {
        if (Content('keyword-search-status') == "We are sorry, the server is not responding...") {
          status = "Please refresh the page and try again...";
        } else {
          status = "We are sorry, the server is not responding...";
        }
      }
      
      ContentSet('keyword-search-status',status);
      seconds = eval(eval(seconds) + 5);
      setTimeout("keyword_check_progress('"+seconds+"')",5000);
    
    }

    ///////////////////////////////////////////////////
    // removes a keyword from keyword search results
    ///////////////////////////////////////////////////
    function keyword_hide(kwd_id) {
      ajax_c++;
      $.get("research_.php?action=keyword_hide&keyword_id="+kwd_id,
        function(data){ ajax_c--; 
      });
      $("#kwd_"+kwd_id).remove();
      
      var keywords_c = 0;
      $("._keyword_table").each(function() {
          keywords_c++;
      });
      
      if (keywords_c < 1) {
        $("#search-results-intro").hide();
        $("#research-results").hide();
        $("#review-create").hide();
      }
      
      // tracking
      if(typeof pageTracker == 'object') {
        pageTracker._trackEvent('Research', 'Keyword Removal', kwd_id);
      }
    }

    ///////////////////////////////////////////////////////
    // runs upon clicking on button below keyword results
    //////////////////////////////////////////////////////
    function keywords_submit(method) {
      
      if (method == "review") { // for new accounts
        GoTo("review");
      } else if (method == "submit") { // for existing accounts
        $.get("research_.php?action=keywords_add", function(data) { 
          GoTo('/account/keywords-submitted.php?event=keywords_added') 
        });
      }
    
    }

///- REVIEW & SIGNUP

    //////////////////////////////////////////////////
    // used to notify about signup error
    //////////////////////////////////////////////////
    function signup_error(element,msg) {
    
      if (document.getElementById(element) != undefined) {
        document.getElementById(element).focus();
      }
      alert(msg);
    
    }


    /////////////////////////////////////////////////
    // verifies signup form before submitting it
    /////////////////////////////////////////////////
    function signup_precheck() {
      
      var msg = "";
      var name_first = Value('name_first');
      var name_last = Value('name_last');
      var email = Value('email');
      var password = Value('password');
      var password_2 = Value('password_2');
      var phone = Value('phone');
      
      var cc_name = Value('cc_name');
      var cc_address = Value('cc_address');
      var cc_city = Value('cc_city');
      var cc_zip = Value('cc_zip');
      var cc_country = Value('cc_country');
      var cc_type = Value('cc_type');
      var cc_number = Value('cc_number');
      var cc_exp_month = Value('cc_exp_month');
      var cc_exp_year = Value('cc_exp_year');
      var cc_cvc = Value('cc_cvc'); 
      
      // user data
      if (name_first == "") {
        signup_error('name_first',"Enter your first name.");
      } else if (name_last == "") {
        signup_error('name_last',"Enter your last name.");
      } else if (email == "") {
        signup_error('email',"Enter your email.");
      } else if (password == "") {
        signup_error('password',"Enter your password.");
      } else if (password_2 == "") {
        signup_error('password_2',"Repeat your password.");
      } else if (password != password_2) {
        signup_error('password_2',"Passwords do not match.");
      } else if (phone == "") {
        signup_error('phone',"Please enter your phone.");
      
      // billing data
      } else if (cc_name == "") {
        signup_error('cc_name',"Please enter your name as it appears on the credit card.");
      } else if (cc_address == "") {
        signup_error('cc_address',"Please enter billing address.");
      } else if (cc_city == "") {
        signup_error('cc_city',"Please enter billing city.");  
      } else if (cc_zip == "") {
        signup_error('cc_zip',"Please enter zip / postal code."); 
      } else if (cc_country == "") {
        signup_error('cc_country',"Please select billing country.");
      } else if (cc_type == "") {
        signup_error('cc_type',"Please select credit card type.");
      } else if (cc_number == "") {
        signup_error('cc_number',"Please enter credit card number.");
      } else if (vld_cc_number(cc_number) == false) {
        signup_error('cc_number',"You have entered an invalid credit card number.");
      } else if (cc_exp_month == "") {
        signup_error('cc_exp_month',"Please select card expiration month.");
      } else if (cc_exp_year == "") {
        signup_error('cc_exp_year',"Please select card expiration year.");
      } else if (cc_cvc == "") {
        signup_error('cc_cvc',"Please enter credit card CVV/CVC, usually located on the back side of the card.");
      } else if (vld_cc_cvc(cc_cvc) == false) {
        signup_error('cc_cvc',"You have entered an invalid CVV/CVC number. Please recheck it (usually located on the back side of the card) and try again.");
        
      // tos  
      } else if (document.getElementById('tos_checkbox').checked == false) {
        signup_error('tos_checkbox','Please accept terms and conditions.');
      
      // if everything is ok
      } else {  
        ajax_done("signup_submit()");    
      }       
    
    }
    
    ////////////////////////////////////////////////////////////
    // attempts signup once inputs are pre-checked
    ////////////////////////////////////////////////////////////
    function signup_submit() {
      
      // disabling the button so that no more submits could be attempted 
      $("#signup-submit").attr("disabled","disabled");
      
      // attempting signup  
      $.post("review_.php?action=signup",{ inputs : current_inputs() },function(data) {
        if (data.substring(0,2) == "OK") {
          GoTo("thankyou");
        } else {
          $("#signup-submit").removeAttr("disabled"); // enabling submit button
          alert(data); // displaying error          
        }
      });

    }
    
    ////////////////////////////////////////////////////////////
    // start autosave
    ////////////////////////////////////////////////////////////
    function signup_autosave() {
      
      $("input, select").bind("blur", function(){
        if (this.name != "") {
          $.ajax({
            type: "POST",
            url: "review_.php",
            data: "action=autosave&input="+this.id+"&value="+SafeInput(this.value),
            beforeSend: function (data) {
              ajax_c++;
            },
            success: function(data){
              ajax_c--;
            }
          });
        }
      });
    
    }
    
    ///////////////////////////////////////////////////////////
    // checks whether promo code is valid
    ///////////////////////////////////////////////////////////
    function check_promo_code() {
    
      $.get("review_.php?action=check_promo_code&promo_code="+Value('promo_code'),function(data) {
        ContentSet('promo_code_results',data);
      });
    
    }
    
///- LOGIN PAGE
    
    //////////////////////////////////////////////////////////////
    // process request for password reminder
    //////////////////////////////////////////////////////////////
    function password_remind() {
    
      $.get("login_.php?action=password_remind&domain="+SafeInput(Value('domain')),function(data) { 
        $("#password_remind_intro").hide();
        $("#password_remind_result").show();
        ValueSet("domain","");
      });
    
    }
    
    
///- AUX

    /////////////////////////////////////////////////////////////
    // waits for ajax calls to be done
    /////////////////////////////////////////////////////////////
    function ajax_done(action) {
      
      if (ajax_c == 0) {
       eval(action);   
      } else if(ajax_loops > 100) {
        GoTo(location.href+"#E-ajax_done");  
      } else {
        ajax_loops++;
        setTimeout('ajax_done("'+action+'")',500);     
      }
    } 
    
    /////////////////////////////////////////////////////////////
    // moves cursor to the end of the input field
    /////////////////////////////////////////////////////////////
    function caretToEnd(input) {
      if (input.createTextRange && !(window.opera)) {
        // ie and not opera (opera supports both methods)
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', input.value.length);
        range.moveStart('character', input.value.length);
        range.select();
      } else {
        // modern browsers
        input.focus();
        input.setSelectionRange(input.value.length, input.value.length); // added to remove default selection
      }
    }

  /////////////////////////////////////////////////////////////
  // check domain and keyword fields to see if they are valid
  // type is either domain or keyword
  // input id is the id of the input
  /////////////////////////////////////////////////////////////
  function verify_input(type,input_id) {
    
    // check input type    
    if(type == 'domain') {      
      var domain = format_domain($("#"+input_id).val());
      
      // now check if it's valid
      if(domain == '' || domain == null || domain == '.com' || domain == 'undefined' || domain == 'undefined.com') {
        return false;
      } else {
        return true;
      }
      
    } else {
      if(type == 'keyword') {        
        var keyword = $("#"+input_id).val();
        
        // now check if it's valid
        if(keyword == '' || keyword == null) {
          return false;
        } else {
          return true;
        }
      }
    }
  }
  
  /////////////////////////////////////////////////////////////
  // format domain input
  /////////////////////////////////////////////////////////////
  function format_domain(domain) {  
        // formatting domain: stripping prefixes
      domain = ReplaceChars(domain,"http://","");
      domain = ReplaceChars(domain,"https://","");
      domain = ReplaceChars(domain,"www.","");
      
      // formatting domain: stripping landing page
      if (domain.indexOf("/") != -1) {
      domain = domain.substring(0,domain.indexOf("/"));
      }
     
     if(domain != null && domain != undefined) {    
        // add .com
        if (domain.indexOf(".") == -1) {
        domain += ".com";
        }
     }
      
      return domain
  }
  
  //////////////////////////////////////////////////////////////////
  // count text input fields that are empty while shouldn't be
  //////////////////////////////////////////////////////////////////
  function current_inputs() {
    var inputs = ''; 
    $("input:text").each(function() {
      inputs+= this.id+"="+this.value+"&";
    });
    return(inputs);
  }
  
  /////////////////////////////////////////////////////////////
  // validates credit card number using LUHN algo
  /////////////////////////////////////////////////////////////
  function vld_cc_number(number) {
 
    // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
    var number=number.replace(/\D/g, '');
   
    // Set the string length and parity
    var number_length=number.length;
    var parity=number_length % 2;
   
    // Loop through each digit and do the maths
    var total=0;
    for (i=0; i < number_length; i++) {
      var digit=number.charAt(i);
      // Multiply alternate digits by two
      if (i % 2 == parity) {
        digit=digit * 2;
        // If the sum is two digits, add them together (in effect)
        if (digit > 9) {
          digit=digit - 9;
        }
      }
      // Total up the digits
      total = total + parseInt(digit);
    }
   
    // If the total mod 10 equals 0, the number is valid
    if (total % 10 == 0) {
      return true;
    } else {
      return false;
    }
  }
  
  function vld_cc_cvc(cvc) {
    cvc=cvc.replace(/\D/g, '');
    if ((cvc.length == 3) || ( cvc.length == 4)) {
      return true;
    } else {
      return false;
    }
  }

  
  ///////////////////////////////////////////////////
  // tracks virtual page views for google analytics
  ///////////////////////////////////////////////////
  function _m_ga_pageview(url) {
    if(typeof pageTracker == 'object') {
      pageTracker._trackPageview(url);
    } 
  }
  
  