url_protocol = 'http';
if(location.protocol=='https:')
{
	url_protocol = 'https';
}
if (document.domain.indexOf('sitemind') > 0)
{
	var SITE_ROOT = url_protocol+'://'+document.domain+'/service_america/';
	var ROOT_PATH = '/service_america/';
}
else if (document.domain.indexOf('16.139.241.51') > 0) //I removed the 1 from 192.168.116.95 so that if would not have a 0 index. not a great solution
{
	var SITE_ROOT = url_protocol+'://'+document.domain+'/';
	var ROOT_PATH = '/';
}
else
{
	var SITE_ROOT = url_protocol+'://'+document.domain+'/';
	var ROOT_PATH = '/';
}

$(document).ready(function() { 
	if(jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && !window["XMLHttpRequest"]) {
		window.location="ie6.php"; }
	
	if (document.URL.indexOf('/admin/') > 0) {
		// These are javascript calls that will only be made in the ADMIN area
		$('a.newWin').click(function(){
			window.open(this.href);
			return false;
		});
		
		if($('#side').length > 0) {
			$('ul.sf-menu').superfish();
			if(menu_sublocation != "") $('#'+menu_sublocation).addClass("on");
			if(menu_location != "") $('#'+menu_location).addClass("on");
		}
		
		/* ADD ADMIN JAVASCRIPTS HERE */
		
	}
	else
	{
		if(!isset('skip_menu')) 
		{
			$('ul.sf-menu').superfish(); //creates the menu
		}
		
		$('a.newWin').click(function(){
			window.open(this.href);
			return false;
		});
		/* ADD PUBLIC JAVASCRIPTS HERE */
		

	}
});

/**************************************************************************************
No need to edit below this point
**************************************************************************************/ 

//clears and replaces text in form input fields and textareas
function clearText(thefield,defaultValue) {
	if(defaultValue=='') { defaultValue = thefield.defaultValue; }
	if (defaultValue==thefield.value) { thefield.value = ""; }
}
function replaceText(thefield,defaultValue) {
	if(defaultValue=='') { defaultValue = thefield.defaultValue; }
	if (thefield.value=="") { thefield.value = defaultValue; }
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
}

function getQueryString(key)
{
    var re = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
    var offset = location.search.search( re );
    if ( offset == -1 ) return null;
    return RegExp.$1;
}

function submitenter(myfield,submitFunction,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		eval(submitFunction)();
		return false;
	}
	else return true;
}

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Cyanide_7 |  */
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
  var keyCode = (isNN) ? e.which : e.keyCode; 
  var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
  if(input.value.length >= len && !containsElement(filter,keyCode)) {
    input.value = input.value.slice(0, len);
    input.form[(getIndex(input)+1) % input.form.length].focus();
  }

  function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
    else
    index++;
    return found;
  }

  function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
  }
  return true;
}

function confirmDelete(delUrl,itemid,title,deleteType) {
	if (confirm("Are you sure you want to delete the "+deleteType+" : "+title+"?")) {
		$.post(SITE_ROOT+delUrl,
			{ 
				operation: 'deleteItem', 
				id: itemid
			},
			function(data){
				gridReload();
			}, 
			"json"
		);
	}
}

function confirmDeleteMultiple(delUrl,items,deleteType) {
	if (confirm("Are you sure you want to delete the selected "+deleteType+"(s)?")) {
		$.post(SITE_ROOT+delUrl,
			{ 
				operation: 'deleteItem', 
				id: items
			},
			function(data){
				gridReload();
			}, 
			"json"
		);
	}
}

function slideDown_prep(el){
	var $el = $(el), height = $el.data("originalHeight"), visible = $el.is(":visible");
	  
	if( !height ){
		height = $el.show().height();
		// update the height
		$el.data("originalHeight", height);
		// if the element was hidden, hide it again
		if( !visible ) $el.hide().css({height: 0});
	}
}

function explode (delimiter, string, limit) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/explode    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
     var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||        typeof arguments[1] == 'undefined' ) {
        return null;
    }
 
    if ( delimiter === '' ||        delimiter === false ||
        delimiter === null ) {
        return false;
    }
     if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;    }
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}

function setUpUnload()
{
	//window.onbeforeunload = null;
	//window.document.body.onbeforeunload = null;
	
	window.onbeforeunload = function() {
		if(current_step == 7)
		{
			$.ajax({
				url: SITE_ROOT+"ajax/service_contracts_process.php",
				type: "post",
				data: { operation: 'clearContractSession' },
				async: false,
				success: function(){
					return ''; //insert custom message here.
				}
			});
		}
		else
		{
			return ''; //insert custom message here.
		}
	};
}

function formProcessSetup(formId)
{
	$('#'+formId+' .errorMsg').slideUp();
	$('#'+formId+' .errorMsg').html('');
	
    if($('#'+formId+' .processing').length > 0) $('#'+formId+' .processing').show();
  	if($('#'+formId+' .btnSubmit').length > 0) $('#'+formId+' .btnSubmit').hide();
}

//-------------rework the show error function + helpers for more flexibility------------------//
function showResult(data, formId, extras)
{	
	/*extras parameters: 
		dont_reset_form = if set will not reset the form
		dont_hide_form = if set will not hide the form
		skip_parent_errors = if set errors will not be placed on the parent elements
		step_content = if set will load up the content  into div
		page_redirect = if set will redirect to the page passed on success
		function_name = if set will call function on form submit success
		use_exact_path = if set will use exact path passed instead of a SITE_ROOT path
		exact_path = path to use for the above option
		dont_scroll_on_error = if set will not scroll to top of page when theres an error
	*/
	$('#'+formId+' .errorMsg').slideUp();
	$('#'+formId+' .errorMsg').html('');
	
    if($('#'+formId+' .processing').length > 0) $('#'+formId+' .processing').show();
  	if($('#'+formId+' .btnSubmit').length > 0) $('#'+formId+' .btnSubmit').hide();
  	
  	//check if result is being passed the new way
	var result; //will hold the value for our result success | error

	if(data[0]==undefined){
		//alert('not defined');
		result = data.result;
	}
	else
	{
		result = data[0].result;
	}
	
  	if(result=="success")
	{
  		if(extras == undefined) { extras = '' } //check if the extras parameters array exists if not set it so that we dont get errors farther down
  		if(extras.dont_reset_form != '1') { resetForm(formId); } //if the dont_reset_form is isnt set then reset the form
		if(extras.step_content != undefined) //check if the ajax page parameter is defined
		{ 
			//alert('load up via ajax: ' + data[1].step_content); 
		   	$("#step_content").hide();	//this has to stay the same because this is where the forms are being loaded into
	   		$("#step_content").load(SITE_ROOT+extras.step_content,function(){
	   			_gaq.push(['_trackPageview', extras.step_content]);

	        	if($('#'+formId+' .btnSubmit').length > 0) $('#'+formId+ ' .btnSubmit').show();
	        	if($('#'+formId+' .processing').length > 0) $('#'+formId+' .processing').hide();
	        	$("#step_content").slideDown();}
	        );
	   		if($('#fbcontent').length > 0) {
        		$('#fancybox-inner').scrollTo(0,100);
        	} else {
        		$.scrollTo(0,800);
        	}
		}
			
		else if(extras.page_redirect != undefined) //check if page redirect parameter is passed
		{ 
			if(extras.use_exact_path =='1')
			{
				//alert(extras.use_exact_path);
				window.location = extras.exact_path;
			}
			else
			{
				//alert('no exact path passed');
				window.location=SITE_ROOT+extras.page_redirect;
			}
		}
		
		else if(extras.function_name != undefined) 
		{ 	
			eval(extras.function_name)();
		}
  		
		else
		{
			if($('#'+formId+' .thankyouMsg').length > 0) $('#'+formId+' .thankyouMsg').slideDown();
			if(extras.dont_hide_form != '1')
			{
				if($('#'+formId).length > 0) $("#"+formId).slideUp();
			}
			else
			{
				if($('#'+formId+' .btnSubmit').length > 0) $('#'+formId+ ' .btnSubmit').show();
	        	if($('#'+formId+' .processing').length > 0) $('#'+formId+' .processing').hide();
			}
			if($('#fbcontent').length > 0) {
        		$('#fancybox-inner').scrollTo(0,100);
        	} else {
        		$.scrollTo(0,800);
        	}
		}
		
	}
	else
	{      
//		if(data[1].step_content != undefined) { alert('load up via ajax: ' + data[1].step_content); }
//		if(data[1].page_redirect != undefined) { alert('go to: ' + data[1].page_redirect); }
//		if(data[1].function_name != undefined) { alert('call this function: ' + data[1].function_name); }
//		if(data[1].dont_hide_form == '1') { alert('DONT HIDE THE FORM!! : ' + data[1].dont_hide_form); }
//		if(data[1].dont_reset_form == '1') { alert('DONT RESET THE FORM!! : ' + data[1].dont_reset_form); }

		showErrors(data,formId,extras);
	}
}

function showErrors(data,formId,extras)
{
	clearErrors(formId);
	
	var newData = new Object();
	if(data[0]==undefined) newData = data;
	else newData = data[0];
	//loop through the JSON array and display the errors
	$.each(newData, function(key,value) {                    
		if(key != "result")
		{
			$('label[for='+key+']').addClass("error");
			$('#'+key).addClass("error");
			if(value!=1) { $("#"+formId+" .errorMsg").html($("#"+formId+" .errorMsg").html()+value); }			
		}
	});
	if($("#"+formId+" .errorMsg").html()=="") { 
		$("#"+formId+" .errorMsg").html("Please correct the errors highlighted in red below"); 
	}
	$("#"+formId+" .errorMsg").slideDown(); 
	
	if($('#fbcontent').length > 0) {
		if(extras.dont_scroll_on_error!='1')
		{
				$('#fancybox-inner').scrollTo(0,100);
		}
	} else {
		if(extras.dont_scroll_on_error!='1')
		{
			$.scrollTo(0,800);
		}
	}	
	if($('#'+formId+' .processing').length > 0) $('#'+formId+' .processing').hide();
	if($('#'+formId+' .btnSubmit').length > 0) $('#'+formId+' .btnSubmit').show();
}

/*extras parameters: 
	clearErrors = if 0, errors will NOT be cleared.  default will clear
*/
function showUploadErrors(data,uploadHolderId,errorElemID,extras)
{
	if(extras.clearErrors != 0) { removeUploadErrors(uploadHolderId); }
	
	$(".fileupload").addClass("error");
	
	var newData = new Object();
	if(data[0]==undefined) newData = data;
	else newData = data[0];

	if(newData[uploadHolderId] != "") {
		$("#"+uploadHolderId+errorElemID).addClass("uploadifyError");
		$('label[for='+uploadHolderId+']').addClass("error");
		
		if(newData[uploadHolderId] != 1) {
			$("#"+uploadHolderId+"Error").html($("#"+uploadHolderId+"Error").html()+'<li>'+newData[uploadHolderId]+'</li>');
		}		
	}
	if($("#"+uploadHolderId+"Error").html()=="") { 
		$("#"+uploadHolderId+"Error").html("<li>We experienced an error when uploading the file(s) in highlighted in red above</li>"); 
	}
	$("#"+uploadHolderId+"Error").slideDown(); 
}

function removeUploadErrors(uploadHolderId)
{
	$("#"+uploadHolderId+"Queue").each(function(){
		$(this).removeClass(uploadHolderId+"uploadifyError");
	});
	$('label[for='+uploadHolderId+']').removeClass("error");
	$("#"+uploadHolderId+"Error").html('');
	$("#"+uploadHolderId+"Error").slideUp(); 
}

function clearErrors(formId)  //safari bug is here!!
{
	$('#'+formId+' input,#'+formId+' textarea,#'+formId+' select').removeClass("error");
	$('#'+formId+' label').each(function(index){
        if(!$(this).hasClass('errorMsg')) $(this).removeClass("error");
    });
}

function resetForm(formId)
{
	//$('[type="text"]').val("");
	$('#'+formId+' .errorMsg').html("");
	$('#'+formId+' textarea').val("");	
	$(':input','#'+formId)
	 .not(':button, :submit, :reset, :hidden, :checkbox , :radio')
	 .val('')
	 .removeAttr('checked')
	 .removeAttr('selected');
	
	clearErrors(formId);
}

function isset(varname) { //works like the php isset function
	if(typeof( window[ varname ] ) != "undefined") return true;
	else return false;
}

function updateLoginStatus()
{
	$('#login_inner').hide();
	$.post(SITE_ROOT+"ajax/customer_process.php",
		{ 
			operation: 'updateLoginStatus'
		},
		function(data){
			$('#login_inner').html(data);
			//$('#login_inner').show();
			//$('#login_inner').show("drop", { direction: "down" }, 1000);
			$('#login_inner').effect("bounce", { times:4, mode: 'show', direction: 'down' }, 300);
			//$('#login_inner').show("puff", { percent:200, mode: 'show'}, 1000);
		}, 
		"html"
	);
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

