url_protocol = 'http';
if(location.protocol=='https:')
{
	url_protocol = 'https';
}
if (document.domain.indexOf('sitemind') > 0)
{
	var SITE_ROOT = url_protocol+'://'+document.domain+'/aplicor/';
	var ROOT_PATH = '/aplicor/';
}
else
{
	var SITE_ROOT = url_protocol+'://'+document.domain+'/';
	var ROOT_PATH = '/';
}

//Add site-wide javascript functions to this doc ready function
$(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();
			
			/*
$('#side').accordion({
				active: (menu_location != '' ? '#'+menu_location : false),	//parseInt(menu_location)
				collapsible: true,
				autoHeight: false,
				navigation: true
			});
*/

			
			if(menu_sublocation != "") $('#'+menu_sublocation).addClass("on");
			if(menu_location != "") $('#'+menu_location).addClass("on");
		}
		
		/* ADD ADMIN JAVASCRIPTS HERE */
		
	}
	else if(document.URL.indexOf('/clients/') > 0)
	{
		$('ul#mainNav').superfish({
			hoverClass:    'current',
			animation:   {opacity:'show',height:'show'},
			delay: 100,
	        autoArrows:  false
		}); 
		$('a.newWin').click(function(){
			window.open(this.href);
			return false;
		});
	}
	else
	{
		// These are javascript calls that will only be made in the PUBLIC area
		//$('ul.sf-menu').superfish();
//		$('ul.sf-menu').superfish({
//			speed:       'fast',                          // faster animation speed 
//	        autoArrows:  false
//		}); 
		$('a.newWin').click(function(){
			window.open(this.href);
			return false;
		});
		
		/* ADD PUBLIC JAVASCRIPTS HERE */
		
		$("#featured a, .take-tour a, footer .iframe").fancybox();
		
	}
});

/**************************************************************************************
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 = function() {
		return ''; //insert custom message here.
	};
}

function formProcessSetup(formId)
{
	$('#errorMsg').slideUp();
	$('#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
	*/
	$('#errorMsg').slideUp();
	$('#errorMsg').html('');
	
    if($('#'+formId+' .processing').length > 0) $('#'+formId+' .processing').show();
  	if($('#'+formId+' .btnSubmit').length > 0) $('#'+formId+' .btnSubmit').hide();
  	
  	if(data[0].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
		{ 
			window.location=SITE_ROOT+extras.page_redirect;
		}
		
		else if(extras.function_name != undefined) 
		{ 	
			eval(extras.function_name)();
		}
  		
		else
		{
			if($('#thankyouMsg').length > 0) $('#thankyouMsg').slideDown();
			if(extras.dont_hide_form != '1')
			{
				if($('#'+formId).length > 0) $("#"+formId).slideUp();
			}
			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) { $("#errorMsg").html($("#errorMsg").html()+value); }			
		}
	});
	if($("#errorMsg").html()=="") { 
		$("#errorMsg").html("Please correct the errors highlighted in red below"); 
	}
	$("#errorMsg").slideDown(); 
	
	if($('#fbcontent').length > 0) {
		$('#fancybox-inner').scrollTo(0,100);
	} else {
		$.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!!
{
	$('input[type="text"],input[type="password"],textarea,select').removeClass("error");
	$('#'+formId+' label').each(function(index){
        if(!$(this).hasClass('errorMsg')) $(this).removeClass("error");
    });
}

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

function getGroupCheckBoxValues(nameValue,numValues)
{
	var i=0;
	var checked = 0;
	var values = '['
    $('input[name="'+nameValue+'[]"]').each(function(){
		if(i != 0) { values += ','; } 
		if($("#"+this.id).attr('checked')) { checked = 1; } else { checked = 0; }
		values += '{"'+nameValue+'":"'+checked+'"}';
		i++;
    });
    if(values.charAt(values.length)==",") values.slice(0, -1);
    values += "]";
    return values; 
}

function getGroupInputValues(nameValue,numValues)
{
	var i=0;
	var values = '['
    $('input[name="'+nameValue+'[]"]').each(function(){
		if(i != 0) { values += ','; } 
		values += '{"'+nameValue+'":"'+$("#"+this.id).val()+'"}';
		i++;
    });
    if(values.charAt(values.length)==",") values.slice(0, -1);
    values += "]";
    return values; 
}

/* Populate a field with a suggested SEO name
 * title: name to base return value off of
 * field_name: form field to write seo name to
 * override: if false only write to the field if it is empty, if true always write to the field no matter what the current value is
 */
function suggestSeoName(title,field_name,override)
{
	if(override == undefined) { override = false; }
	if((override || $('#'+field_name).val() == "") && title != "") 
	{
		seoName = title.replace(/\'/g,"");
		seoName = seoName.replace(/\./g,"");
		seoName = seoName.replace(/\(/g,"");
		seoName = seoName.replace(/\)/g,"");
		seoName = seoName.replace(/\'/g,"");
		seoName = seoName.replace(/\"/g,"");
		seoName = seoName.replace(/ /g,"-");

		$('#'+field_name).val(seoName.toLowerCase());
	}
}

