//===========Zen Library===============

//==== checkForm function that checks for blank and valid email in a form ====
//pre-condition: Must have an Email field with id='Email' for it to check Email properly
//Can use real world names for ids of other form fields, such as id="First Name"
//HTMLcontent can be used to ignore the HTML flag as an ID
//second parameter - IGNORE ARRAY
//A global variable used to contain input field IDs that are to be ignored.


function checkForm(formID,ignoreArray)
{
	
ignoreArray = ignoreArray.split(",");

	if(document.getElementById(formID))
	{
		theForm		= document.getElementById(formID);
		numofInputs	= theForm.length-0; //minus the submit button and key

//=======Cycle through each input=======
		for(i=0;i<numofInputs;i++)
		{
	
		ignoreVal	= false;
//======Cycle through ignore list=======
		for(ig=0;ig<ignoreArray.length;ig++)
		{
			if(theForm[i].id == ignoreArray[ig])
			{
			ignoreVal = true;
			break;
			}
		}


			if(theForm[i].value == "" && !ignoreVal)
			{
			alert("Please specify a value for: " + theForm[i].id);
			theForm[i].focus();
			return false;
			}
			else if(theForm[i].value != "")
			{

/* CMS SPECIFIC FIELDS, THIS STUFF CAN BE COMMENTED OUT IF NOT BEING USED */

//==========PICTURE VALIDATION============

if(theForm[i].id == "picture1" || theForm[i].id == "picture2" || theForm[i].id == "picture3" || theForm[i].id == "picture4" || theForm[i].id == "picture5")
			{

			picInputValid = 0;

			checkPic = checkMIME(".jpg",theForm[i].value);
			
			if(checkPic == true)
			picInputValid =1;
			/*
			checkPic = checkMIME(".png",theForm[i].value);
				if(checkPic)
				picInputValid =1;			
			checkPic = checkMIME(".gif",theForm[i].value);
				if(checkPic)
				picInputValid =1;			
			*/
			
				if(picInputValid == 0)
				{
				alert("Only jpg is an acceptable image format.");
				theForm[i].focus();
				return false;		
				}
			}	

if((theForm[i].id == "Phone" || theForm[i].id =="Sec. Phone") && theForm[i].value != "")
	{
				testPhoneLen = theForm[i].value;
	

//Check for numerics
//====================================================================	

//XXX-xxx-xxxx
				firstTest = testPhoneLen.substr(0,3);				
				testNumeric = isNumeric(firstTest);
				
					if(!testNumeric)
					{
					alert("Please enter phone numbers as: 702-111-2222");
					theForm[i].focus();
					return false;						
					}


//xxx-XXX-xxxx

				firstTest = testPhoneLen.substr(4,3);				
				testNumeric = isNumeric(firstTest);
				
					if(!testNumeric)
					{
					alert("Please enter phone numbers as: 702-111-2222");
					theForm[i].focus();
					return false;						
					}

//xxx-xxx-XXXX

				firstTest = testPhoneLen.substr(8,4);				
				testNumeric = isNumeric(firstTest);
				
					if(!testNumeric)
					{
					alert("Please enter phone numbers as: 702-111-2222");
					theForm[i].focus();
					return false;						
					}

//check Dashes
				testDash = testPhoneLen.charAt(3);	
				
					if(testDash != "-")
					{
					alert("Please enter phone numbers as: 702-111-2222");
					theForm[i].focus();
					return false;							
					}

//check Dashes
				testDash = testPhoneLen.charAt(7);	
				
					if(testDash != "-")
					{
					alert("Please enter phone numbers as: 702-111-2222");
					theForm[i].focus();
					return false;							
					}					
					

			}

//=================MENU PDF =================
if(theForm[i].id == "pdfFile")
{
checkPDF = checkMIME(".pdf",theForm[i].value);
	
	if(!checkPDF)
	{
	alert("Only PDF is an acceptable menu format.");
	theForm[i].focus();
	return false;				
	}
	
}

//PDF VALIDATION
if(theForm[i].id == "special1")
{

			picInputValid = 0;

			checkPic = checkMIME(".pdf",theForm[i].value);
			
			if(checkPic == true)
			picInputValid =1;

				if(picInputValid == 0)
				{
				alert("Only pdf is an acceptable specials format.");
				theForm[i].focus();
				return false;		
				}	
}

//==========HTML CONTENT IS A RESERVED ID FOR A TEXT AREA THAT ALLOW HTML CONTENT============			
		
		if(theForm[i].id == "Comments" || theForm[i].id == "Special Details")
				{
				var HTMLtemp = NoHTML(theForm[i].value);

				if(!HTMLtemp)
				{
				alert("<,>, and ~ are invalid characters.");
				theForm[i].focus();
				return false;					
				}
				}
		

//==========CHECK FOR numeric============

			if(theForm[i].id == "Zip Code")
			{
				testNumeric = true;
				testNumeric = isNumeric(theForm[i].value);
				
				if(!testNumeric)
				{
				alert("Please enter a valid zip code. e.g. 89118");
				theForm[i].focus();
				return false;
				}
			}

//===========CHECK FOR VALID EMAIL=============			
			if(theForm[i].id == "Email")
			{
				var isEmailTemp = IsEmail(theForm[i].value);
				if(!isEmailTemp)
				{
				alert("Please enter a valid email.");
				theForm[i].focus();
				return false;					
				}		
			}

//===========CHECK FOR Password validation=============			
//pre-condition: needs password and password2 as IDs for this portion to work
			if(theForm[i].id == "password2")
			{
			checkPw = verifyPasswords();
			
				if(!checkPw)			
				{
				alert("Your passwords do not match.");
				theForm[i].focus();
				return false;						
				}
			}
		
//FOR MAIN SEARCH FORM
if(formID == "searchForm_main" && document.getElementById('foodtype').value == "" && document.getElementById('cuisinetype').value == "NULLCUISINE")
{
	alert("You must either specify a craving or select a Cuisine type.");
	return false;
}
		
			}	//end else
		} //end for	


//MEMBER AREA
if(formID == "listingUpdate")
{

var checked = false;

	for(i=1;i<=6;i++)
	{
		if(document.getElementById('menuOption'+i).checked)
		{
		checked = true;
		break;
		}
	}
	

	if(!checked)
	{
	alert("Please select a menu option.");
	document.getElementById('menuOption0').focus();
	return false;				
	}
	else
	{
		//check copy and paste option
		if(document.getElementById('menuOption5').checked && document.getElementById('menu').value == "")
		{
		alert("Please Copy + Paste a menu.");
		$('menu').focus();
		return false;					
		}
		else if(document.getElementById('menuOption5').checked && document.getElementById('menu').value != "")
		{
		var HTMLtemp = NoHTML($('menu').value);

			if(!HTMLtemp)
			{
				alert("< and > are invalid characters.");
			$('menu').focus();
			return false;					
			}			
		}
		
		//check to make sure website field is filled out since option 2 is checked
		if(document.getElementById('menuOption2').checked && document.getElementById('Website').value == "")
		{
		alert("Please provide a website address.");
		$('Website').focus();
		return false;					
		}
		
	}
}	


		if(document.getElementById('key'))
		document.getElementById('key').value = getURL();
	}
	else
	alert("No Form Specified with that ID.");
}

//CHECK FORM 2 - a new form intended to phase out the function above
function checkForm2(formID,ignoreArray)
{
	
ignoreArray = ignoreArray.split(",");

	if(document.getElementById(formID))
	{
		theForm		= document.getElementById(formID);
		numofInputs	= theForm.length-0; //minus the submit button and key

//=======Cycle through each input=======
		for(i=0;i<numofInputs;i++)
		{
	
		ignoreVal	= false;
//======Cycle through ignore list=======
		for(ig=0;ig<ignoreArray.length;ig++)
		{
			if(theForm[i].id == ignoreArray[ig])
			{
			ignoreVal = true;
			break;
			}
		}


			if(theForm[i].value == "" && !ignoreVal)
			{
			alert("Please specify a value for: " + theForm[i].title);
			theForm[i].focus();
			return false;
			}
			else if(theForm[i].value != "")
			{

//SPECIFIC ACTIONS ON FIELDS
		if(theForm[i].id == "purl")
		{
		re = /^[A-Za-z]+$/;
			
			if(!re.test(theForm[i].value))
			{
			alert("Invalid characters for Simple URL, please only use text.");
			theForm[i].focus();
			return false;			
			}
		
		}
		
			}	//end else
		} //end for	

		if(document.getElementById('key'))
		document.getElementById('key').value = getURL();
	}
	else
	alert("No Form Specified with that ID.");
} //end checkForm2

//==== Password Verify Function ====
//Pre-condition: password and password2 must be the Name and IDs of the password fields
//Post-condtion: returns boolean 
function verifyPasswords()
{

pass1	= document.getElementById('password').value;
pass2	= document.getElementById('password2').value;

//alert("p1:" + pass1 + " p2:" + pass2);

if(pass1 != pass2)
return false;
else
return true;

}

//==== NoQuotesApos function ====
function NoQuotesApos(sText)
{
var whereisAT = sText.indexOf("'");

if(whereisAT == -1)
return false;
   
var whereisDOT = sText.indexOf('"');  

if(whereisDOT == -1)
return false;

//if makes through checks, return true     
return true;
}


//==== Email Check function ====

function IsEmail(sText)
{
var whereisAT = sText.indexOf('@');

if(whereisAT == -1)
return false;
   
var whereisDOT = sText.indexOf('.');  

if(whereisDOT == -1)
return false;

//if makes through checks, return true     
return true;
}

//==== HTML Check function ====
//checks to make sure no HTML tags are in the form

function NoHTML(sText)
{
var whereisAT = sText.indexOf('>');

if(whereisAT != -1)
return false;
   
var whereisDOT = sText.indexOf('<');  

if(whereisDOT != -1)
return false;

var whereisDOT = sText.indexOf('~');  

if(whereisDOT != -1)
return false;

//if makes through checks, return true     
return true;

}


//==== getURL function ====
//returns the URL in a hidden field to make sure people are not injecting our mail form
//by checking where the form is coming from
//pre-condition: requires a field with an id='key'
function getURL()
{
test = location.href;

test= test.split("/");
str = "";
for(i=0;i<(test.length-1);i++)
{
	if(i == 0)
	str = test[i]+"/";
	else
	str = str + test[i] + "/";
}
return str;
}

function getPage()
{
test = location.href;

test= test.split("/");
str= test[test.length-1];

if(str == "") //index page
str = "index.php";

return str;
}


//FOR DELETING

function verifyDeleteItem(theItem)
{
for (i=0;i<document.getElementById(theItem).length;i++)
   {
     var current = document.getElementById(theItem).options[i];
		
		if(current.selected == true)
		groupname = document.getElementById(theItem).options[i].text;	
   }
var answer = confirm ("Are you sure you want to delete the item: " + groupname + "?")	

if(answer)
return true;
else
return false;	
}

//============FOR NUMBER VERIFICATION=============
function isNumeric(theVal)
{
pattern = /^\d+$/;
if(pattern.test(theVal) ==false)
return false;
else
return true;
}


//For MIME validation
//Pre-condition: Extension is a string such as ".gif" ".jpg", inputvalue is the value to be checked against
//Post returns whether the value is of an acceptable MIME type
function checkMIME(extension,inputValue)
{

	inputValue = inputValue.toLowerCase();	
	var getLength =  inputValue.length;
	//extension check
	var check = inputValue.substring(getLength-4,getLength)

//jpeg hack
if(check == ".jpeg")
check = ".jpg";

//alert(check + " " + extension);

	if(check != extension)
	return false;
	else
	return true;
} //end checkMIME


//FOR LISTINGS PAGE
//---------------------

//Swap Pic
function swapPic(picSrc)
{
	if(picSrc != "")
	document.getElementById('MainPic').src = "listing_images/" + picSrc; 
}

function Pause(lngMillis){
	var date = new Date();
	var curDate = null;

	do{
		curDate = new Date();
	}
	while(curDate-date < lngMillis);
}

//Toggle COmment Form
function toggleCommentForm(show)
{

if(show)
{
document.getElementById('commentLink').innerHTML = "<a href='javascript:toggleCommentForm(false);' class='commentLink'>Hide Review Form</a>";
document.getElementById('commentForm').style.display ='block';
document.getElementById('commentSubmitText').style.display = 'none';
}
else
{
document.getElementById('commentLink').innerHTML = "<a href='javascript:toggleCommentForm(true);' class='commentLink'>Write a Review</a>";	
document.getElementById('commentForm').style.display ='none';
}

}


//Process Comment Form
function processCommentForm()
{
	
	if(document.getElementById('comments').value == "")
	{
	alert("Please enter a comment.");
	document.getElementById('comments').focus();
	return;
	}
	
	var poststr = "comments=" + encodeURI( document.getElementById('comments').value ) + "&rating=" + encodeURI( document.getElementById('rating').value) + "&lid=" + encodeURI(document.getElementById('lid').value );
	
   makePOSTRequest('comment_submit.php', poststr);	
	
}


function createXMLHttpRequest() {
      try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
      try { return new XMLHttpRequest(); } catch(e) {}
      alert("XMLHttpRequest not supported");
      return null;
}


 function makePOSTRequest(url, parameters) {
      http_request = false;
	
	http_request = createXMLHttpRequest();
      
	  if (http_request.overrideMimeType)
            http_request.overrideMimeType('text/html');
	  
	  //build body for Form Post
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

function alertContents() 
{
if(http_request.readyState == 4) 
{

	if (http_request.status == 200)
	{
	result = http_request.responseText;
	//alert(result);
	
	if(result == "success")
	{
	document.getElementById('comments').value = '';
	document.getElementById('rating').value = '1';
	document.getElementById('commentSubmitText').style.display = 'block';
	toggleCommentForm(false);
	}
	
	} 
	else 
	alert('There was a problem with the request.');       
}
}

var lastMenu = null;
function showMenuItem(menuID)
{

if(lastMenu != null)
document.getElementById(lastMenu).style.display = 'none';


document.getElementById(menuID).style.display = 'block';

lastMenu = menuID;
}

//For Zipcode Layer
//===================================

function togglepopularZipcodes(showLayer)
{
if(showLayer)
document.getElementById('PopularZipcodes').style.display = 'block';
else
document.getElementById('PopularZipcodes').style.display = 'none';
}

function populateZipcodeField(theVal)
{
document.getElementById('Zip Code').value = theVal;
togglepopularZipcodes(false);
}

//For support page
//===================================

function verifyEmailForm(formName)
{

	if (formName.email.value == "") 
	{
		alert( "Please enter a valid e-mail address." );
		formName.email.focus();
		return false ;
	}	
	else
	{
		var isEmailTemp = IsEmail(formName.email.value);
	
		if(!isEmailTemp)
		{
		alert("Please enter a valid email. (e.g. user@allcravings.com)");
		formName.email.focus();
		return false;					
		}		
	}
	
	formName.referringURL.value = getURL();

}

//For SMS Feature in Listings Page
//==================================

function sendtoPhone()
{
window.open("printer-friendly.php");
}


//toggle div

function toggleDiv(divID,toggle)
{
	if(document.getElementById(divID))
	document.getElementById(divID).style.display = toggle;
}

//for coupon/specials feature
function toggleCoupons(toggleIndex)
{
	if(toggleIndex == 1)
	{
		toggleDiv('Specials','none');
		toggleDiv('Coupons','block');
		toggleDiv('Promotions','none');
	}
	else if(toggleIndex == 2)
	{
		toggleDiv('Specials','block');
		toggleDiv('Coupons','none');	
		toggleDiv('Promotions','none');
	}
	else if(toggleIndex == 3)
	{
		toggleDiv('Specials','none');
		toggleDiv('Coupons','none');
		toggleDiv('Promotions','block');
	}	
}

function ieSpaceCheck()
{
var x 			= navigator;
//alert(x.appVersion);

var checkBrowser = x.appVersion.indexOf('MSIE 7.0');

	//IE 7
	if(checkBrowser != -1)
	{
	toggleDiv('ieSpace','block');
	toggleDiv('ieSpace2','block');
	return;
	}

var checkBrowser = x.appVersion.indexOf('MSIE 6.0');

	//IE 6
	if(checkBrowser != -1)
	{
	toggleDiv('ieSpace','block');
	toggleDiv('ieSpace2','block');
	return;
	}

}


/* Flash Detection */

function detectFlash()
{
/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.4
*/
var FlashDetect = new function(){
    var self = this;
    self.installed = false;
    self.raw = "";
    self.major = -1;
    self.minor = -1;
    self.revision = -1;
    self.revisionStr = "";
    var activeXDetectRules = [
        {
            "name":"ShockwaveFlash.ShockwaveFlash.7",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash.6",
            "version":function(obj){
                var version = "6,0,21";
                try{
                    obj.AllowScriptAccess = "always";
                    version = getActiveXVersion(obj);
                }catch(err){}
                return version;
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        }
    ];
    /**
     * Extract the ActiveX version of the plugin.
     * 
     * @param {Object} The flash ActiveX object.
     * @type String
     */
    var getActiveXVersion = function(activeXObj){
        var version = -1;
        try{
            version = activeXObj.GetVariable("$version");
        }catch(err){}
        return version;
    };
    /**
     * Try and retrieve an ActiveX object having a specified name.
     * 
     * @param {String} name The ActiveX object name lookup.
     * @return One of ActiveX object or a simple object having an attribute of activeXError with a value of true.
     * @type Object
     */
    var getActiveXObject = function(name){
        var obj = -1;
        try{
            obj = new ActiveXObject(name);
        }catch(err){
            obj = {activeXError:true};
        }
        return obj;
    };
    /**
     * Parse an ActiveX $version string into an object.
     * 
     * @param {String} str The ActiveX Object GetVariable($version) return value. 
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseActiveXVersion = function(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    };
    /**
     * Parse a standard enabledPlugin.description into an object.
     * 
     * @param {String} str The enabledPlugin.description value.
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseStandardVersion = function(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    };
    /**
     * Parse the plugin revision string into an integer.
     * 
     * @param {String} The revision in string format.
     * @type Number
     */
    var parseRevisionStrToInt = function(str){
        return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
    };
    /**
     * Is the major version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required major version.
     * @type Boolean
     */
    self.majorAtLeast = function(version){
        return self.major >= version;
    };
    /**
     * Is the minor version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required minor version.
     * @type Boolean
     */
    self.minorAtLeast = function(version){
        return self.minor >= version;
    };
    /**
     * Is the revision version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required revision version.
     * @type Boolean
     */
    self.revisionAtLeast = function(version){
        return self.revision >= version;
    };
    /**
     * Is the version greater than or equal to a specified major, minor and revision.
     * 
     * @param {Number} major The minimum required major version.
     * @param {Number} (Optional) minor The minimum required minor version.
     * @param {Number} (Optional) revision The minimum required revision version.
     * @type Boolean
     */
    self.versionAtLeast = function(major){
        var properties = [self.major, self.minor, self.revision];
        var len = Math.min(properties.length, arguments.length);
        for(i=0; i<len; i++){
            if(properties[i]>=arguments[i]){
                if(i+1<len && properties[i]==arguments[i]){
                    continue;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }
    };
    /**
     * Constructor, sets raw, major, minor, revisionStr, revision and installed public properties.
     */
    self.FlashDetect = function(){
        if(navigator.plugins && navigator.plugins.length>0){
            var type = 'application/x-shockwave-flash';
            var mimeTypes = navigator.mimeTypes;
            if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
                var version = mimeTypes[type].enabledPlugin.description;
                var versionObj = parseStandardVersion(version);
                self.raw = versionObj.raw;
                self.major = versionObj.major;
                self.minor = versionObj.minor; 
                self.revisionStr = versionObj.revisionStr;
                self.revision = versionObj.revision;
                self.installed = true;
            }
        }else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
            var version = -1;
            for(var i=0; i<activeXDetectRules.length && version==-1; i++){
                var obj = getActiveXObject(activeXDetectRules[i].name);
                if(!obj.activeXError){
                    self.installed = true;
                    version = activeXDetectRules[i].version(obj);
                    if(version!=-1){
                        var versionObj = parseActiveXVersion(version);
                        self.raw = versionObj.raw;
                        self.major = versionObj.major;
                        self.minor = versionObj.minor; 
                        self.revision = versionObj.revision;
                        self.revisionStr = versionObj.revisionStr;
                    }
                }
            }
        }
    }();
};
FlashDetect.JS_RELEASE = "1.0.4";

return FlashDetect.installed;

}


