///- 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 and popup video
  /////////////////////////////////////////////////////////
  $(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");
	  if ($('#column-right').html().replace(/\s|\t|\r|\n/g,'') == '') {
      	$("#column-right").append('<div class="sidebar-submit" style=""><a href="#" onclick=\'movie_popup_play()\'><img src="images/quicktour-side.jpg" /></a></div>');
      	$("#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" style="*display:none"><a href="#" onclick=\'movie_popup_play()\' ><img src="images/quicktour-side.jpg" /></a></div>');
			  $("#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			
		*/
		('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

    
  /////////////////////////////////////////////////////////////////
  // pop up video when user click on the trigger
  /////////////////////////////////////////////////////////////////
  $(document).ready(function() {
    $("#movieTrigger").bind('click',movie_popup_play);
  })

  function movie_popup_play(){
  

      if(typeof pageTracker == 'object') {
        pageTracker._trackEvent('Homepage', 'Quicktour Play');
      } 
      
      // $("#movieWrapper").show(); sendEvent('playpause'); // this would only be used for preloading
      
      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');
      
      //necessary for IE7 and IE6
      movieHolder.className = 'video';
      tbOverlay.className='TB_overlayBG';
      
      // required for ie6
      var cta = document.getElementById('cta');
      var arrow = document.getElementById('find-domain-arrow');
      if(arrow){ // only on homepage
       arrow.style.zIndex = '0';
       cta.style.zIndex = '0';
      }
   
      movieHolder.appendChild(closeWindow);
      movieHolder.appendChild(moviePlaceholder);
      window.document.body.appendChild(movieHolder);
      window.document.body.appendChild(tbOverlay);

      $('#moviePlaceholder').html('<iframe width="640" height="480" src="http://www.youtube.com/embed/8YECzO9HmUE?rel=0&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>');
  
  }
 

  
  
  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);
   
   //required for ie6
   var cta = document.getElementById('cta');
   var arrow = document.getElementById('find-domain-arrow');
   if(arrow){ // only on homepage
    arrow.style.zIndex = '950';
    cta.style.zIndex = '950';
   }
  }
    
    
  ///////////////////////////////////////////////////
  // 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;
    })
  })
   
    
///- 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 > 10) { // maximum allowed AJAX call is for 5 seconds
        alert("We are sorry, but it seems like we are having some connectivity issues.\nTo fix that, this window will be reloaded and you might have to re-enter some of the data to proceed. Sorry again for the inconvenience.");
        DataTrade('review_.php?action=report_error&error_type=ajax_loop');
        GoTo(location.href);  
      } 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());
      $("#domain-search").val(domain);
      
      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("/"));
      }

      // now lets get rid of all disallowed characters
      // this will also garble SQL injection / XSS
      domain = domain.replace(/[^A-Za-z\.0-9-]/g,'');
      domain = domain.replace(/^-/,'');
      domain_var = domain.split('.');
      for (var j = 0; j < domain_var.length; j++) {
        domain_var[j] = domain_var[j].replace(/-$/,'');
      }
      domain = domain_var.join('.');

     
     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,select,textarea").each(function() {
      inputs.push(this.id+"="+this.value);
    });
    if ($('#btoken').val()!=null) {
		inputs.push('btoken='+$('#btoken').val());
    }
    return(inputs.join('&'));
  }
  
  ///////////////////////////////////////////////////////
  // shortens the string by throwing out the middle part
  // @example  asdfgghjkl5677890.php -->  asdfg...0.php 
  ///////////////////////////////////////////////////////
  function str_contract(string,limit) {
    var output = string;

    if (string.length > limit) {
     limit_1 = (limit / 2) - 7;
     limit_2 = string.length - (limit / 2) + 3;
     output = string.substring(0,limit_1) + "....." + string.substring(limit_2);
    } 
   return output;
  }

  
/**
* Carousel for rotating quotes treated as
* $(document).ready(function(){
*	$.get('content/homepage/testimonials.php',{},function(data){
*		try {
*			data = data.split(';');
*			for( var i = 0; i < data.length; i++ ) {
*				data[i] = data[i].replace(/\n/g,'');
*				data[i] = data[i].replace(/^\s+/,'');
*				data[i] = data[i].replace(/\s+$/,'');
*			}
*			//Carousel.load(data);
*		} catch (e) {
*			// put 3 quotes there hard coded
*		}
*	});
* });
* Could be the case we still use this, kept anyway
*/
function CarouselC() {
	var quotes = [];
	this.interval = null;
	this.inter = 10000; //default
	this.howmany = 0;
	this.show_num = 2;
	_self = this;
	this.load = function(data, type, show)
	{
		if (type != undefined && type == 'quote1') {
			this.inter = 5000;
			this.show_num = 1;
		}
		if ($.isFunction(show)) {
			this.show = show;
		}
		quotes = data;
		setIntervals();
	};
	this.show = function (data)
	{
		// generic show() can be overwritten
		if (data != undefined) {
			str = '';
			for (var i = 0; i < data.length; i++ ) {
				if (data[i] != undefined) {
					var q = data[i][0];
					var p = (data[i][1]!=undefined)?data[i][1].split('|'):['',''];
					if (q == '') {
						continue;
					}
					str += '<div class="testimonial-wrap">'+
					'<blockquote style="text-align:justify;">' + 
					q + '</blockquote>' + 
					'<p><strong>' + p[0] + '</strong>' + p[1] + '</p></div>';
				}
			}
			if (str == '') {
				return ;
			}
			$('#testimonial-enc').fadeOut(1000);
			function sleep(millis) 
			{
				var date = new Date();
				var curDate = null;
				do { curDate = new Date(); } 
				while(curDate-date < millis);
			}
			sleep(1000);
			$('#testimonial-enc').html(str);
			$('#testimonial-right-subhead').css('height',false);
			$('#testimonial-enc').fadeIn(1000);
		}
	};
	var setIntervals = function()
	{
		_self.interval = setInterval('Carousel.next();', _self.inter);
	};
	var clearIntervals = function()
	{
		clearInterval(_self.interval);
	};
	this.next = function ()
	{
		var start = this.howmany * this.show_num;
		appendedQuotes = [];
		count = start;
		str = '';
		reset = false;
		for (var i = start; i < (start + this.show_num); i++) {
			if (quotes[i] == undefined) {
				reset = true;
				break;
			} else if (
				this.show_num == 1 && 
				quotes[i][0].split(' ') > 40
			)
			{
				continue;
			}
			append(quotes[count]);
			count++;
		}
		if (reset == true) {this.howmany=0;}
		//else if( (this.howmany*this.show_num) >= (quotes.length)) { this.howmany=0; }
		else { this.howmany++; }
		if (appendedQuotes.length >= 1) {
			this.show(appendedQuotes);
		}
	};
	var appendedQuotes = [];
	var append = function(quotes_)
	{
		str = '';
		var data = quotes_.split(':');
		var q = data[0];
		var p = data[1];
		appendedQuotes.push([q,p]);
	};
}
//don't create until used
//var Carousel = new CarouselC;

