if(top.location.href != window.location.href){
	top.location.href = window.location.href;
}

function CheckAll(bChecked){
	var tg = document.getElementsByTagName("input");
	for(i = 0; i < tg.length; i++){
		if(tg.item(i).name == "action[]"){
			tg.item(i).checked = bChecked;
		}
	}
}

// Equivalent of PHP function count()
function count(arr){
	c = 0;
	for(i in arr){
		if(arr[i]){
			c++;
		}
	}
	return c;
}

function openWindow(url, w, h){
	windowprops = 'width=' + w + ',height=' + h +',left=10,top=10,scrollbars=no,status=yes,toolbar=no,location=no,directories=no,resizable=yes';
	popup = window.open(url, 'newWin', windowprops);
	popup.focus();
	return popup;
}

function openWindowWithScroll(url, w, h){
	windowprops = "width=" + w + ",height=" + h +",left=10,top=10,scrollbars=yes,status=yes,toolbar=no,location=no,directories=no,resizable=yes";
	popup = window.open(url, 'newWin', windowprops);
	popup.focus();
	return popup;
}

var xmlHttp = httpGetObject();

function validateInsSamedayPayday(f){
	if(f.zipcode.value == ''){
		alert('Please enter your zipcode.');
		f.zipcode.focus();
		return false;
	} else if(!validZIP(f.zipcode.value)){
		alert('Please enter valid 5-digits zipcode.');
		f.zipcode.focus();
		return false;
	} else {
		f.action = 'http://www.samedaypayday.com/apply-now.php?cmd=10&zip=' + f.zipcode.value;
		return true;
	}
}

function validateSearch(f){
	if(f.search.value == ''){
		alert('Please enter search condition.');
		f.search.focus();
		return false;
	} else {
		return true;
	}
}

function validState(str){
	re = /^[a-zA-Z]{2}$/;
	if(re.test(str)){
		return true;
	} else {
		return false;
	}
}

function validZIP(val){
	re = new RegExp(/^\d{5,5}$/);
	if(val.match(re)){
		return true;
	} else {
		return false;
	}
}

function existingZIP(val){
	if(xmlHttp){
		xmlUrl = '/existingzip.php?zipcode=' + val;
		xmlHttp.open('GET', xmlUrl, false);
		xmlHttp.send(null);
		return !!parseInt(xmlHttp.responseText);
	} else {
		alert('httpGetObject does not exist');
		return false;
	}
}

function validAreaCode(str){
	areacode = str.substring(0,3);
	if(existingAreaCode(areacode)){
		return true;
	} else {
		return false;
	}
}

function existingAreaCode(val){
	if(xmlHttp){
		xmlUrl = '/existingareacode.php?areacode=' + val;
		xmlHttp.open('GET', xmlUrl, false);
		xmlHttp.send(null);
		return !!parseInt(xmlHttp.responseText);
	} else {
		alert('httpGetObject does not exist');
		return false;
	}
}

function switchClass(obj, strClassName){
	obj.className = strClassName;
}

function gotoURL(strUrl){
	location = strUrl;
}

// this closes popup window and goes to "url"
function gotoApply(url){
	if(window.opener){
		window.opener.location = url;
		self.close();
	} else {
		return false;
	}
}

function copyrightYear(startYear){
	d = new Date();
	if(startYear != d.getFullYear()){
		return startYear + " - " + d.getFullYear();
	} else {
		return startYear;
	}
}

function UpdateArticlesCall(){
	if(xmlHttp){
		xmlHttp.open('GET', 'updatecontent.php?action=1', true);
		xmlHttp.onreadystatechange = handleRequest;
		xmlHttp.send(null);
	} else {
		alert('httpGetObject does not exist');
		return false;
	}
}

function handleRequest(){
	if(xmlHttp.readyState == 1){
		setStatusMsg('Articles Updating. Please wait ...');
	}
	if(xmlHttp.readyState == 2){
		setStatusMsg('Sending...');
	}
	if(xmlHttp.readyState == 3){
		setStatusMsg('In process...');
	}
	if(xmlHttp.readyState == 4){
		if(xmlHttp.status == 200){
			alert(xmlHttp.responseText);
			document.location = 'headlines.php?reset=1&action=new';
		} else if(xmlHttp.status == 404){
			setStatusMsg('File not found');
		} else {
			setStatusMsg('XML error');
		}
	}
}

function setStatusMsg(msg){
	var div = document.getElementById('divStatus');
	if(msg){
		div.innerHTML = msg;
		div.style.display = 'block';
	} else {
		div.style.display = 'none';
	}
}

function UpdateILeadzVehiclesCall(){
	if(xmlHttp){
		xmlHttp.open('GET', 'updateileadzvehicles.php?action=1', true);
		xmlHttp.onreadystatechange = handleILeadzVehiclesRequest;
		xmlHttp.send(null);
	} else {
		alert('httpGetObject does not exist');
		return false;
	}
}

function handleILeadzVehiclesRequest(){
	if(xmlHttp.readyState == 1){
		setStatusMsg('Vehicles Updating. Please wait ...');
	}
	if(xmlHttp.readyState == 2){
		setStatusMsg('Sending...');
	}
	if(xmlHttp.readyState == 3){
		setStatusMsg('In process...');
	}
	if(xmlHttp.readyState == 4){
		if(xmlHttp.status == 200){
			alert(xmlHttp.responseText);
			document.location = 'updateileadzvehiclesform.php?reset=1&action=new';
		} else if(xmlHttp.status == 404){
			setStatusMsg('File not found');
		} else {
			setStatusMsg('XML error');
		}
	}
}

// ------ Cookies Functions Begin ------

/**
 * Sets a Cookie with the given name and value.
 *
 * name			Name of the cookie
 * value			Value of the cookie
 * [expires]	Expiration date of the cookie (default: end of current session)
 * [path]		Path where the cookie is valid (default: path of calling document)
 * [domain]		Domain where the cookie is valid
 *					(default: domain of calling document)
 * [secure]		Boolean value indicating if the cookie transmission requires a
 *					secure transmission
 */
function setCookie(name, value, expires, path, domain, secure){
	document.cookie = name + '=' + escape(value) +
	((expires) ? '; expires=' + expires.toGMTString() : '') +
	((path) ? '; path=' + path : '') +
	((domain) ? '; domain=' + domain : '') +
	((secure) ? '; secure' : '');
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name){
	var dc = document.cookie;
	var prefix = name + '=';
	var begin = dc.indexOf('; ' + prefix);
	if(begin == -1){
		begin = dc.indexOf(prefix);
		if(begin != 0){
			return null;
		}
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(';', begin);
	if(end == -1){
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain){
	if(getCookie(name)){
		document.cookie = name + '=' +
		((path) ? '; path=' + path : '') +
		((domain) ? '; domain=' + domain : '') +
		'; expires=Thu, 01-Jan-70 00:00:01 GMT';
	}
}

// Set cookie
cookieVAR = getCookie('insuranceUSA');

if(!cookieVAR){
	var date = new Date();
	var id = date.getYear() + '' + date.getDate() + '' + date.getMonth() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds();

	sVar = id + ' ' + document.referrer + ' ' + navigator.userAgent;

	// Cookies will expire in 20 years
	days = 365 * 20;

	date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
	setCookie('insuranceUSA', sVar, date, '/');
}
// ------ Cookies Functions Begin ------

function isInt(val){
	val = val.toString();
	if(val == ''){
		return false;
	} else {
		return (!isNaN(val) && val.indexOf('.', 0) == -1);
	}
}

function fixNum(el){
	el.value = el.value.replace(/\D/g, '');
}

/**
 * Trim string functons
 */
function RTrim(str){
	w_space = String.fromCharCode(32);
	v_length = str.length;
	strTemp = '';
	if(v_length < 0){
		return '';
	}
	iTemp = v_length -1;

	while(iTemp > -1){
		if(str.charAt(iTemp) == w_space){

		} else {
			strTemp = str.substring(0, iTemp + 1);
			break;
		}
		iTemp = iTemp - 1;
	}
	return strTemp;
}

function LTrim(str){
	w_space = String.fromCharCode(32);
	if(v_length < 1){
		return '';
	}
	v_length = str.length;
	strTemp = '';

	iTemp = 0;

	while(iTemp < v_length){
		if(str.charAt(iTemp) == w_space){

		} else {
			strTemp = str.substring(iTemp, v_length);
			break;
		}
		iTemp = iTemp + 1;
	}
	return strTemp;
}

function Trim(str){
	if(str.length < 1){
		return '';
	}
	str = RTrim(str);
	str = LTrim(str);
	return str;
}

function rsMenuOpen(id)
{
	document.getElementById(id).style.display = document.getElementById(id).style.display == 'none' ? 'block' : 'none';
	document.getElementById(id+'Header').className = document.getElementById(id+'Header').className == 'open' ? '' : 'open';
}


function newSublevel()
{
	var tbody = document.createElement('tbody');
	var newID = getNewUrlId();
	
	var tr = document.createElement('tr');
	tr.className = 'tableDataDark';
	
	var td = document.createElement('td');
	td.style.textAlign = 'right';
	td.innerHTML = 'Sublevel Title:';
	tr.appendChild(td);
	
	td = document.createElement('td');
	
	var input = document.createElement('input');
	input.type = 'hidden';
	input.name = 'sublevelActive[]';
	input.value = '1';
	td.appendChild(input);
	td.appendChild(document.createTextNode(' '));
	
	input = document.createElement('input');
	input.id = 'sublevelTitle'+newID;
	input.type = 'text';
	input.name = 'sublevelTitle[]';
	input.className = 'formSublevelText';
	input.size = 68;
	input.maxlength = 128;
	input.onkeyup = function() { updateURLs(); isSpecialSublevel(this) }
	td.appendChild(input);
	td.appendChild(document.createTextNode(' '));
	
	input = document.createElement('input');
	input.type = 'button';
	input.onclick = function() {this.value = expandSublevel(this.parentNode.parentNode) }
	input.value = 'Expand';
	td.appendChild(input);
	td.appendChild(document.createTextNode(' '));
	
	input = document.createElement('input');
	input.type = 'button';
	input.onclick = function() { moveSublevel(this, -1) }
	input.value = 'Move Up';
	td.appendChild(input);
	td.appendChild(document.createTextNode(' '));
	
	input = document.createElement('input');
	input.type = 'button';
	input.onclick = function() { moveSublevel(this, 1) }
	input.value = 'Move Down';
	td.appendChild(input);
	tr.appendChild(td);
	
	input = document.createElement('input');
	input.type = 'button';
	input.value = 'Disable';
	input.onclick = function() { this.value = enableSublevel(this) }
	td.appendChild(document.createTextNode(' '));
	td.appendChild(input);
	
	
	input = document.createElement('input');
	input.type = 'button';
	input.onclick = function() { deleteSublevel(this) }
	input.value = 'Delete';
	td.appendChild(input);
	tr.appendChild(td);
	tbody.appendChild(tr);	
	
	tbody.appendChild(createSublevelRow('URL:', 'sublevelURL[]', false, newID));
	tbody.appendChild(createSublevelRow('Body Title:', 'bodyTitle[]'));
	tbody.appendChild(createSublevelRow('Meta Title:', 'metaTitle[]'));
	tbody.appendChild(createSublevelRow('Meta Description:', 'metaDescription[]'));
	tbody.appendChild(createSublevelRow('Meta keywords:', 'metaKeywords[]'));
	tbody.appendChild(createSublevelRow('Content:', 'sublevelContent[]', true));
	
	document.getElementById('sublevels').appendChild(tbody);
}

function createSublevelRow(text, name, textarea, urlID)
{
	var tr = document.createElement('tr');
	tr.className = 'tableDataLight';
	tr.style.display = 'none';
	
	var td = document.createElement('td');
	td.style.textAlign = 'right';
	td.innerHTML = text;
	tr.appendChild(td);
	
	td = document.createElement('td');
	
	if(textarea)
	{
		var tArea = document.createElement('textarea');
		tArea.name = name;
		tArea.rows = 25;
		tArea.cols = 100;
		tArea.className = 'formTextArea2';
		td.appendChild(tArea);
	}
	else
	{
		var input = document.createElement('input');
		input.type = 'text';
		input.name = name;
		input.className = 'formSublevelText';
		input.size = 68;
		input.maxlength = 128;
		
		if(urlID)
		{
			input.id = 'sublevelURL'+urlID;
			input.className = 'readonlyInput';
		}
		
		td.appendChild(input);
	}
	
	tr.appendChild(td);
	
	return tr;
}

function expandSublevel(el, alwaysCollapse)
{
	var currentRow = el.nextSibling;
	var isHidden = null;
	
	if(alwaysCollapse)
		isHidden = false;
	
	do
	{
		if(currentRow.nodeType == 3)
			continue;
		
		if(isHidden === null)
			isHidden = currentRow.style.display == 'none';
		
		currentRow.style.display = isHidden ? '' : 'none';
	}
	while(currentRow = currentRow.nextSibling);
	
	return isHidden ? 'Collapse' : 'Expand';
}

function moveSublevel(el, offset)
{
	var tbody = el.parentNode.parentNode.parentNode;
	
	if(offset == -1)
	{
		var previous = tbody.previousSibling;
		
		while(previous !== null && previous.nodeType == 3)
			previous = previous.previousSibling;
		
		if(previous)
			tbody.parentNode.insertBefore(tbody, previous);
	}
	else
	{
		var next = tbody.nextSibling;
		
		while(next !== null && next.nodeType == 3)
			next = next.nextSibling;
		
		if(next)
			tbody.parentNode.insertBefore(tbody, next.nextSibling);
	}
}

function updateURLs()
{
	var dURL = document.getElementById('dURL').value;
	
	var urls = document.getElementsByName('sublevelTitle[]');
	
	for(var i = 0; i < urls.length; i++)
	{
		var id = urls[i].id.replace('sublevelTitle', '');
		
		document.getElementById('sublevelURL'+id).value = sublevelURL(dURL, urls[i].value);
	}
	
	document.getElementById('companyURL').value = document.getElementById('host').value+sublevelURL('', dURL);
	
	while(dURL.indexOf(' ') != -1)
	{
		dURL = dURL.replace(' ', '-');
	}
	
	return dURL;
}

function sublevelURL(company, sublevel)
{
	if(!sublevel)
		return '';
	
	var str = company+(company ? '-' : '')+sublevel;
	
	str = str.replace('&', 'and');
	
	str = str.replace(/[^a-z0-9]+/gi, '-');
	
	return str+'.php';
}

function getNewUrlId()
{
	var urls = document.getElementsByName('sublevelTitle[]');
	
	var last = 0;
	for(var i = 0; i < urls.length; i++)
	{
		var id = urls[i].id.replace('sublevelTitle', '');
		
		if(id > last)
			last = id;
	}
	
	return last+1;
}

function deleteSublevel(el)
{
	var answer = confirm("Are you sure you want to delete this sublevel?");
	
	if(answer === false)
		return false;
	
	el.parentNode.parentNode.parentNode.parentNode.removeChild(el.parentNode.parentNode.parentNode);
}

function isSpecialSublevel(el)
{
	var expandButton = el.nextSibling;
	
	if(expandButton.nodeType == 3)
		expandButton = expandButton.nextSibling;
	
	var deleteButton = expandButton.nextSibling;
	
	do
	{
		deleteButton = deleteButton.nextSibling;
	}
	while(deleteButton.value != 'Delete')
	
	if(el.value.toLowerCase() == 'news' || el.value.toLowerCase() == 'reviews')
	{
		expandSublevel(el.parentNode.parentNode, true);
		
		deleteButton.disabled = true;
		expandButton.disabled = true;
		expandButton.value = 'Expand';
	}
	else
	{		
		deleteButton.disabled = false;
		expandButton.disabled = false;
	}
}

function enableSublevel(el)
{
	var isActive = el.value == 'Disable';
	var trChildren = el.parentNode.childNodes;
	var isSpecial = false;
	
	if(isActive)
		expandSublevel(el.parentNode.parentNode, true);
	
	for(var i = 0; i < trChildren.length; i++)
	{
		if(trChildren[i].nodeType == 3 || trChildren[i] == el)
			continue;
		
		if(trChildren[i].type == 'hidden')
		{
			trChildren[i].value = isActive ? '0' : '1';
			continue;
		}
		
		if(trChildren[i].type == 'text')
			isSpecial = trChildren[i].value.toLowerCase() == 'news' || trChildren[i].value.toLowerCase() == 'reviews';
		
		if(isSpecial && trChildren[i].type == 'button' && (trChildren[i].value == 'Delete' || trChildren[i].value == 'Expand'))
			continue;
		
		if(isActive && trChildren[i].value == 'Collapse')
			trChildren[i].value = 'Expand';
		
		trChildren[i].disabled = isActive ? true : false;
	}
	
	return isActive ? 'Enable' : 'Disable';
}

function companyMoveDown(button, toMove)
{
	if(!toMove)
	{
		var toMove = button.parentNode;
		
		//get parent tr 
		while(toMove.nodeType != 1 || !toMove.id)
		{
			toMove = toMove.parentNode;
		}
	}
	
	var first = companyGetID(toMove);
	var second = 0;
	
	var nextValid = null;
	var inBetween = [];
	var next = toMove.nextSibling;
	
	//find the next element on the same level (if any) and all the elements in between
	do
	{
		if(!nextValid)
		{
			if(next.nodeType != 1 || !next.id)
				continue;
			
			if(companyOnSameLevel(next.id, toMove.id))
			{
				nextValid = next;
				
				second = companyGetID(next);
				
				//break;
			}
			else
				inBetween[inBetween.length] = next;
		}
		
		if(nextValid) //next element found - see if it has any children (levels) that must be skipped
		{
			if(next.nextSibling.nodeType != 1)
				continue;
			
			//reached either the next sibling with the same parent, a top level/end of table or a superior level
			if(companyOnSameLevel(next.nextSibling.id, toMove.id) || !next.nextSibling.id 
				|| (companyGetLevel(next.nextSibling) !== false && companyGetLevel(next.nextSibling) < companyGetLevel(toMove)))
			{
				nextValid = next;
				
				break;
			}
		}
	}
	while(next = next.nextSibling);
	
	//if there is a next element on the same level...
	if(nextValid)
	{
		dimScreen(true);
		
		//...move all current elements after it
		var toInsertBefore = nextValid.nextSibling;
		
		while(toInsertBefore.nodeType != 1)
		{
			toInsertBefore = toInsertBefore.nextSibling;
		}
		
		nextValid.parentNode.insertBefore(toMove, toInsertBefore);
		
		for(var i = 0; i < inBetween.length; i++)
		{
			nextValid.parentNode.insertBefore(inBetween[i], toInsertBefore);
		}		
		
		var xmlHttp = httpGetObject();
		
		xmlUrl = '/admin/swapposition.php?first='+first+'&second='+second;
		xmlHttp.open('GET', xmlUrl, false);
		xmlHttp.send(null);
		
		setTimeout("dimScreen(false)", 200);
		
		return !!parseInt(xmlHttp.responseText);
	}
	
	return false;
}

function companyOnSameLevel(first, second)
{
	var id = first.substr(0, first.lastIndexOf('['));
	
	return id == second.substr(0, second.lastIndexOf('['))
}

function companyGetID(el)
{
	if(el.nodeType != 1)
		return false;
	
	var level = '';
	
	var tmp = el.id.split('[');
	
	return tmp[3].substr(0, tmp[3].length-1);
}

function companyGetLevel(el)
{
	if(el.nodeType != 1)
		return false;
	
	var level = '';
	
	var tmp = el.id.split('[');
	
	return tmp[2].substr(0, tmp[2].length-1);
}

function companyMoveUp(el)
{
	var toMove = el.parentNode;
	
	//get parent tr 
	while(toMove.nodeType != 1 || !toMove.id)
	{
		toMove = toMove.parentNode;
	}
	
	var prev = toMove.previousSibling;
	
	//use moveDown on the sibling above current
	do
	{
		if(prev.nodeType != 1)
			continue;
		
		if(companyOnSameLevel(prev.id, toMove.id)) 
		{
			companyMoveDown(null, prev);
			
			return;
		}
	}
	while(prev = prev.previousSibling);
}

function debug(message)
{
	document.getElementById('debug').innerHTML += message+" ";
}

function dimScreen(on)
{
	var w = document.body.scrollWidth > document.body.clientWidth ? document.body.scrollWidth : document.body.clientWidth;
	var h = document.body.scrollHeight > document.body.clientHeight ? document.body.scrollHeight : document.body.clientHeight;
	
	document.getElementById('dimmer').style.width = w;
	document.getElementById('dimmer').style.height = h;
	document.getElementById('dimmer').style.display = 'block';
	
	document.getElementById('dimmer').style.display = on ? 'block' : 'none';
}


if (typeof jQuery != 'undefined') {  
    
    $(function() {
		
		var t = $("input[name=zipcode]");		
		$(t).each(function() {
					$(this).val("");
				  });
		
		var t1 = $(t).not(".smallZipSb").eq(0);
		if (!$(t1).hasClass("reviewQB")) {
			$(t1).focus();	
		}
	});
} 

