/* Global Functions */

function testFirewall() {
	
	// Requires JQUERY!
	
	$("body").append("<div id='mmf_firewall_test' style='display:none;'></div>");

	$.get(_MMF_API_DIR + "test.php", function(data){
	  $("#mmf_firewall_test").html(data);
	});
	
	setTimeout(function() {
		var strTest = $("#mmf_firewall_test").html();
		if (strTest == "") {
			window.location.href = "/firewall_settings";	
		}
	}, 2500);

}

String.prototype.toTitleCase = function() {
	//lowercase the whole string
	var ls = this.toLowerCase();
	//turn it into an array by splitting at spaces
	var la = ls.split(" ");
	//loop through word array
	for (var i = 0; i < la.length; i++ ) {
		//replace first letter with uppercase version
		la[i] = la[i].charAt(0).toUpperCase() + la[i].slice(1);
	}
	//rejoin words and return the new string
	return la.join(" ");
};

String.prototype.trim = function () { 
	return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};


String.prototype.stripHtml = function () { 
	var strOuput = this.replace(/(<([^>]+)>)/ig,"");	
	strOuput = strOuput.trim();
	return strOuput;
};

function setSelectListToValue(strValue, oSelect){
	if (oSelect != null){
		for(var i=0; i<oSelect.length; i++){
			if(oSelect.options[i].value == strValue){ oSelect.selectedIndex = i; }
		}
	}
}

function populateSelectList(lstSelect, strURL, strSelectedValue, strDefaultValue, imgLoader, strInitialOption) {
	
	// Disable Select List and Reset
	lstSelect.disabled = true;
	lstSelect.options.length = 0;
	
	// Display Loader
	if (imgLoader) {
		imgLoader.style.display = "";
	}
	
	// Set Selected Value to Default
	if (strSelectedValue == "") { 
		strSelectedValue = strDefaultValue;
	}
	
	if (strInitialOption && strInitialOption != "" && strInitialOption != "undefined") {
		lstSelect.options[lstSelect.options.length] = new Option(strInitialOption, "", false);
	}
	
	// Ajax Populate from Remote JSON
	$.getJSON(strURL,
        function(data){
        	if (data.result.output.options) {
				$.each(data.result.output.options, function(i,option){

					var strValue = option.value.toTitleCase();
					var strName = stripslashes(htmlentities(option.name.toTitleCase()));
					var o = lstSelect.options.length;
					var bolSelected = ("" + strValue == "" + strSelectedValue ? true : false);
					
					lstSelect.options[o] = new Option(strName, strValue);
					
					if (bolSelected) {
						lstSelect.selectedIndex = o;
					}

				});
			}
        });
        
	// Hide Loader
	if (imgLoader) {
		imgLoader.style.display = "none";
	}
	
	// Enable Select List
	lstSelect.disabled = false;
	
}

function ReadCookie(cookieName) {
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return ""; 
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length; 
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString()+"; path=/";
}

function formWizardShowStep(intStep)
{
	if (validateFormWizard(intStep))
	{
		$('div.wizard_step').hide();
		$('#wizard_step_'+intStep).show();
		$('#txtWizardStep').val = intStep;
		$('#wizard_step_display > ul > li').removeClass();
		$('#wizard_step_'+intStep+'_display').addClass('selected');
		
		var offset = $('#wizard_step_'+intStep).offset().top;
		$('html,body').animate({scrollTop: offset}, 10);
	}
}
		
function toggleDiv(elCheckbox, strDivID) {
	var elDiv = document.getElementById(strDivID);
	if (elCheckbox.checked) {
		elDiv.style.display = "block";
	} else {
		elDiv.style.display = "none";
	}
}

function toggleFieldDisplay(elSelectList, strValue, strFieldID) {
	var elField = document.getElementById(strFieldID);
	if (elSelectList[elSelectList.selectedIndex].value == strValue) {
		elField.style.display = "inline";
	} else {
		elField.style.display = "none";
	}
}

function showDiv(divID) {
	var elDiv = document.getElementById(divID);
	if (elDiv) {
		elDiv.style.display = 'block';
	}	
}

function hideDiv(divID) {
	var elDiv = document.getElementById(divID);
	if (elDiv) {
		elDiv.style.display = 'none';
	}	
}

function copyTextField(elSourceTextField, strTargetID) {
	var elTargetTextField = document.getElementById(strTargetID);
	if (elSourceTextField.value != "" && elTargetTextField.value == "") {
		elTargetTextField.value = elSourceTextField.value;
	}
}

function copySelectList(elSourceList, strTargetID) {
	var elTargetList = document.getElementById(strTargetID);
	if (elSourceList.selectedIndex != 0 && elTargetList.selectedIndex == 0) {
		setSelectListToValue(elSourceList[elSourceList.selectedIndex].value, elTargetList);
	}
}

function numbersOnly(txtValue) {
	txtValue.value = txtValue.value.replace(/[^0-9.\-:]/g, "");
}

function isDate(txtDate) {
    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    if ((txtDate.value.match(RegExPattern)) && (txtDate.value!='')) {
        return true;
    } else {
        return false;
    } 
}

function isNumeric(strString) {
   var strValidChars = "0123456789.-";
   var strChar;
   var boolNumeric = true;

   if (strString.length == 0) return false;

   for (i = 0; i < strString.length && boolNumeric == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) { boolNumeric = false; }
	}
	return boolNumeric;
}

function makeXHR(){
	var x;
	if(window.XMLHttpRequest){
		x = new XMLHttpRequest();
	}
	else if (window.ActiveXObject){
		x = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return x;
}

function browserDetect() {
	// Browser Warning
	// (navigator.userAgent.indexOf("MSIE 6.0; Windows NT 5.0") == -1) 
	if (
		(BrowserDetect.browser == "Firefox" && +BrowserDetect.version >= 1.5) ||
		(BrowserDetect.browser == "Explorer" && +BrowserDetect.version >= 6.0) ||
		(BrowserDetect.browser == "Safari" && +BrowserDetect.version >= 400) ||
		(BrowserDetect.browser == "OmniWeb") ||
		(BrowserDetect.browser == "Gecko") ||
		(BrowserDetect.browser == "Camino") )
	    {
	   
		// Supported Browser

	} else {
		// Redirect
		if(confirm('Your browser (' + BrowserDetect.browser + ',' + BrowserDetect.version + ')' + ' is not fully supported/validated.  Click OK to proceed to our download center to obtain a compatible browser, or cancel to proceed to the site (unsupported)')) {
			window.location = "/download_center";
		}
	}
}

function listSort(elLink, txtSortUp, txtSortDown) {
	txtSort = document.getElementById("txtSortBy");
	strCurrentSort = txtSort.value;

	if (strCurrentSort == txtSortUp) {
		txtSort.value = txtSortDown;
	} else {
		txtSort.value = txtSortUp;
	}

	document.frmSearch.submit();
}

function openPopUp(strTargetUrl) {
	var page = strTargetUrl;
	winproperties = "height=800,width=1000,top=10,left=10,screenX=10,screenY=10,directories=no,location=no,menubar=yes,resizable=yes,scrollbars=yes,status=no,toolbar=no";
	window.open(page, "newWindow", winproperties);
}

function convertUserDate(strDate, strDateFormat) {
	
	var dtOutput = new Date()

	switch (strDateFormat) {
		case "MM/DD/YYYY":
		  var arrDate = strDate. split("/");
		  dtOutput.setFullYear(arrDate[2], arrDate[0]-1, arrDate[1]);
		  break;
		case "DD/MM/YYYY":
		  var arrDate = strDate. split("/");
		  dtOutput.setFullYear(arrDate[2], arrDate[1]-1, arrDate[0]);
		  break;
		case "YYYY-MM-DD":
		  var arrDate = strDate. split("-");
		  dtOutput.setFullYear(arrDate[0], arrDate[1]-1, arrDate[2]);
		  break;
	}
	
	return dtOutput;
}

function convertUserDistance(dblDistance, strMeasurementUnit) {
	if (strMeasurementUnit == "metric" || strMeasurementUnit == "hybrid") {
		dblDistance =  Math.round(0.621371192 * dblDistance, 2);
	}
	return dblDistance;
}


function htmlentities( s ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    var div = document.createElement('div');
    var text = document.createTextNode(s);
    div.appendChild(text);
    return div.innerHTML;
}

function stripslashes( str ) {
    // Un-quote string quoted with addslashes()
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_stripslashes/
    return str.replace('/\0/g', '0').replace('/\(.)/g', '$1');
}

Number.prototype.ordinal=function(){
    var nModTen = this % 10;
    return (this + ['th','st','nd','rd'][nModTen > 3 ? 0 : ( this % 100 - nModTen != 10) * nModTen]);
}

function getWeekdayCount(dtDate) {
	
	var arrWeekday=new Array(7);
	arrWeekday[0]="Sunday";
	arrWeekday[1]="Monday";
	arrWeekday[2]="Tuesday";
	arrWeekday[3]="Wednesday";
	arrWeekday[4]="Thursday";
	arrWeekday[5]="Friday";
	arrWeekday[6]="Saturday";

	var strWeekdayCount = "";
	
	var intDay = dtDate.getDate();
	var intMonth = dtDate.getMonth();
	var intYear = dtDate.getYear();
	var intDayOfWeek = dtDate.getDay();
	
	// Date Fix
	if (intYear < 2000) intYear += 1900;

	var dtTestDate = new Date()
	var c = 0;
	
	for (var d = 0; d <= intDay; d++) {
		dtTestDate.setFullYear(intYear, intMonth, d);
		if (dtTestDate.getDay() == intDayOfWeek) { c++; }
	}
	
	return c.ordinal() + " " + arrWeekday[intDayOfWeek];
}

function toggleCheckboxes(idForm) {
	if (!document.getElementById){ return; }
	if (!document.getElementsByTagName){ return; }
	var inputs = document.getElementById(idForm).getElementsByTagName("input");
	for(var x=0; x < inputs.length; x++) {
		if (inputs[x].type == 'checkbox'){
			inputs[x].checked = !inputs[x].checked;
		}
	}
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];

	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}; 

var RecaptchaOptions = {
  theme : 'custom',
  custom_theme_widget: 'recaptcha_widget'
}; 
