/*
 * Global Variables
 */
var isLoadedData = false;
var currentHost = 'http://' + window.location.host + '/';
if (location.host == 'localhost:90') {
	currentHost += 'Gvina/'
}
var leeChilds;/*the searchresultes LI childnodes*/
var counter = 0;
var cheeseList = new Array();
var mailto ="m"+"a"+"i"+"l"+"t"+"o"+":";
var gvina = "@"+"gvina"+"."+"co"+"."+"il";
var jsonContent = '';

/* cookies functions
function setCookie(idNum) {
	if (idNum == '123456') {
		document.cookie = "login=ok";
		$('screen').style.display = 'none';
		$('screen').innerHTML = '';
	}
}

function getCookie() {
	if(document.cookie.indexOf("login=ok") > -1)  {
		$('screen').style.display = 'none';
		$('screen').innerHTML = '';
	}
	else {
		return false
	}
}
*/

/* Form  functions*/


function responder_validation() {
	var inputs = document.getElementById('rspform').getElementsByTagName('input');
	var filter = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+){1,4}$/;

	for (a=0; a<inputs.length; a++) {
		switch (inputs[a].name) {
			case 'fields[subscribers_email]':
				if (!filter.test(inputs[a].value)) {
					alert('כתובת הדוא"ל אינה חוקית');
					inputs[a].focus();
					return false;
				}

				break;
			case 'fields[subscribers_name]':
				if(inputs[a].value=='') {
					alert('נא לרשום שם');
					inputs[a].focus();
					return false;
				}

				break;
		}
	}

	return true;
}


function processForm(sForm,sPackage,sUrl) {
	var oXmlPut = new xmlHttpReq();
	oXmlPut.open('POST', sUrl, true);
	oXmlPut.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	oXmlPut.setRequestHeader("Content-length", sPackage.length);
	oXmlPut.setRequestHeader("Connection", "close");
	oXmlPut.onreadystatechange = function(){
		 if (oXmlPut.readyState == 4) {
	         if (oXmlPut.status == 200) {
	            rsvp = oXmlPut.responseText;
	            $(sForm).innerHTML = rsvp;
	         } else {
	            $(sForm).innerHTML = '<p id="validationProblem">בעייה בשליחת ההודעה. אנו מתנצלים על אי הנוחות. אנא פנה אלינו בטלפון: 03-5474276.</p>';
	         }
      	}
		else {
			$(sForm).innerHTML = 'אנא המתן...'
		}
	}
	oXmlPut.send(sPackage);
}

function displayErrorOnForm (sElement) {
	$(sElement).className = 'error';
	$(sElement).onkeydown = function() {
		this.className = '';
		noError = true;
		for (var i = 0;i < 3;i++) {
			$('err' + i).innerHTML = '';
		}
	}
}

function sendForm(theForm,sActionUrl) {
	var rgxPhone = /^[0-9]{7,}$/;
	var rgxMail = /^[a-zA-Z0-9]*@[a-zA-Z0-9]*\.[a-z]*$/;
	var noError = true;
	var errMessage = new Array('','','');
	var inputs = $(theForm).elements;
	if (inputs['name'].value.length < 2) {
		errMessage[0] = 'בעייה בשם ->&nbsp;';
		displayErrorOnForm('name');
	}
	if (!rgxPhone.test(inputs['phone'].value)) {
		errMessage[1] = 'בעייה בטלפון ->&nbsp;';
		displayErrorOnForm('phone');
	}
	if (inputs['email'].value.indexOf('@') < 0) {
		errMessage[2] = 'בעייה באימייל ->&nbsp;';
		displayErrorOnForm('email');
	}
	for (var i = 0;i < 3;i++) {
		if(errMessage[i] != '') {
			noError = false;
			$('err' + i).innerHTML = errMessage[i];
		}
	}
	if (noError) {
		var sb = new stringBuffer();
		for (var i = 0;i < $(theForm).elements.length;i++) {
			sb.append($(theForm).elements[i].name);
			sb.append(' = ')
			sb.append(encodeURI($(theForm).elements[i].value));
			if (i != $(theForm).elements.length - 1) {
				sb.append('&');
			}
		}
		var theData = sb.toString();
		processForm(theForm,theData,sActionUrl);
	}
}

/*General Functions*/

function toggleFaq(faqId) {
	if (document.getElementById('faq' + faqId).style.display != 'block') {
		document.getElementById('faq' + faqId).style.display = 'block';
	}
	else {
		document.getElementById('faq' + faqId).style.display = 'none';
	}

}
function doar(correspondent){
   location = mailto + correspondent + gvina + "?subject=From [Please add your name here]&body=Just to know that you are flesh and blood and not a robot, would you kindly add your name to the subject line. Thanks! - " + correspondent ;
}

function popUp(sFile,sWidth,sHeight) {
	var popUp = window.open(sFile + '.php',sFile,'width=' + sWidth + ',height=' + sHeight + ',status=no,menu=no');
	popUp.focus();
}

function drawFlashObject(sName, sContainter, sWidth, sHeight) {
	var sb = new stringBuffer();
	sb.append('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="');
	sb.append(sWidth);
	sb.append('" height="');
	sb.append(sHeight);
	sb.append(" id=");
	sb.append(sName);
	sb.append('" align="middle">');
	sb.append('<param name="allowScriptAccess" value="sameDomain" />');
	sb.append('<param name="movie" value="Images/');
	sb.append(sName);
	sb.append('.swf" />');
	sb.append('<param name="quality" value="high" />');
	sb.append('<param name="wmode" value="transparent" />');
	sb.append('<param name="bgcolor" value="#F9EA9E" />');
	sb.append('<embed src="Images/');
	sb.append(sName);
	sb.append('.swf" quality="high" wmode="transparent" bgcolor="#F9EA9E" width="');
	sb.append(sWidth);
	sb.append('" height="');
	sb.append(sHeight);
	sb.append(" name=");
	sb.append(sName);
	sb.append('" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	$(sContainter).innerHTML = sb.toString();/*'leftPromo'*/
}

function putRandomPix(picId,which) {
	if($(picId)) {
		var currentPic = $(picId);
		var randomPic = Math.round(10*Math.random());
		if (randomPic == 0) {
			randomPic = 11;
		}
		currentPic.src = "Images/" + which + randomPic + ".jpg";
	}
}

/*Cheese engine functions*/

function goUp(sParam) {
	counter++;
	if(counter >= cheeseList.length) {
		counter = 0;
	}
	$('selected').innerHTML = cheeseList[counter];
	$('resultList').innerHTML = populateCheeseList(cheeseList[counter],sParam);
}

function goDown(sParam) {
	counter--;
	if(counter < 0) {
		counter = cheeseList.length-1;
	}
	$('selected').innerHTML = cheeseList[counter];
	$('resultList').innerHTML = populateCheeseList(cheeseList[counter],sParam);
}

function populateCheeseList(theItem, sParam) {
	var sb = new stringBuffer();
	var idCounter = 0;
	for(i=0;i<jsonContent.length;i++) {
		if (eval('jsonContent[i].' + sParam) == theItem) {
			sb.append('<li onclick = "showInfo(this);">');
			sb.append(jsonContent[i].cheeseName);
			sb.append('</li>');
			idCounter ++;
		}
	}
	leeChilds = idCounter;
	return sb.toString();
}

function showInfo(theCheese) {
	$('sayCheese').src = 'Images/cheesePicLoader.gif';
	var cheeseName = theCheese.innerHTML;
	var sb = new stringBuffer();
	for (var i=0;i<jsonContent.length;i++) {
		if(jsonContent[i].cheeseName == cheeseName) {
			$('countryTD').innerHTML = jsonContent[i].country;
			$('milkTD').innerHTML = jsonContent[i].milk;
			$('textureTD').innerHTML = jsonContent[i].texture;
			var couponLocation = 'coupon.php?cheeseid=' + jsonContent[i].id;
			var couponWindow = false;
			$('couponLocation').onclick = function() {
				couponWindow = window.open(couponLocation,'couponLocation','width=569, height=449');
				couponWindow.focus();
			}
			if(jsonContent[i].image != '' || typeof(jsonContent[i].image) == 'undefined') {
				$('sayCheese').src = 'Images/' + jsonContent[i].image;
			}
			else {
				$('sayCheese').src = 'Images/moo.jpg';
			}
			sb.append('<h2>');
			sb.append(jsonContent[i].cheeseName);
			sb.append(' ');
			sb.append(jsonContent[i].latinName)
			sb.append('</h2><p>');
			sb.append(jsonContent[i].content);
			sb.append('</p>');
			break;
		}
	}
	$('cheeseInfo').innerHTML = sb.toString();
	show('popUp');
}


function exhaustList(sParam) {
	var tmpArray = new Array();
	var tmp = '';
	var cheeseTextureCounter = 0;
	for(var i=0;i<jsonContent.length;i++) {
		cheeseList[i] = eval('jsonContent[i]' + '.' + sParam);
		}
	cheeseList = cheeseList.sort();
	for(var i=0;i<cheeseList.length;i++) {
		if (cheeseList[i] != tmp) {
			tmpArray[cheeseTextureCounter] = cheeseList[i];
			cheeseTextureCounter ++;
		}
		tmp = cheeseList[i];
	}
	cheeseList = tmpArray;
	$('selected').innerHTML = cheeseList[0];
	$('resultList').innerHTML = populateCheeseList(cheeseList[0],sParam);
	$('goUp').onclick = function() {goUp(sParam)};
	$('goDown').onclick = function() {goDown(sParam)};
}

function switchSearch(cNode) {
	$('param').innerHTML = cNode.innerHTML;
	var param = cNode.parentNode.id;
	if(cNode.parentNode.id == 'cheeseName') {
		var autoComplete = document.createElement("input");
		autoComplete.type = 'text';
		$('selected').innerHTML = '&nbsp;';
		$('selected').appendChild(autoComplete);
		autoComplete.focus();
		$('navArrows').style.display = 'none';
		autoComplete.value = 'הקלד כאן';
		autoComplete.onkeyup = function() {suggest(this.value)};
	}
	else {
		$('navArrows').style.display = 'block';
		exhaustList(param);
	}
}

function suggest(theInput) {
	var regExp = eval('/^' + theInput +'/');
	var sb = new stringBuffer();
	for (var i=0;i<jsonContent.length;i++) {
		if (jsonContent[i].cheeseName.match(regExp)) {
			sb.append('<li onclick = showInfo(this)>');
			sb.append(jsonContent[i].cheeseName);
			sb.append('</li>');
		}
	}
	$('resultList').innerHTML = sb.toString();
}

/* Effect functions */

function show(theElement) {
	new Effect.Appear(theElement,{ duration: 0.4 });
	new Effect.Appear('film',{ duration: 0.4, to:0.5-0.0 });
}

function hide(theElement) {
	new Effect.Fade(theElement,{ duration: 0.4 });
	new Effect.Fade('film',{ duration: 0.4 });
}

/*Init function*/
function init() {
	if($('help')) {
		document.getElementById('help').onclick = function() {
			//document.getElementById('whatisCaptcha').style.display = 'block';
			show('whatisCaptcha');
		}
		document.getElementById('whatisCaptcha').onclick = function() {
			//this.style.display = 'none';
			hide(this);
		}
	}

	/*
	if($('checkPass')) {
			$('screen').style.display = 'block';
			$('checkPass').onclick = function() {
				var passWValue = $('passW').value;
				setCookie(passWValue);
			}
			getCookie();
	}
	*/


	/*putRandomPix('leftPlaceHolder','leftPic');
	putRandomPix('rightPlaceHolder','rightPic');*/


	if ($('news')) {
		initializemarquee();
	}

	var param;

	if ($('searchResults')) {
		getJsonData('jsonSource.php',true);

		param  = 'texture';
		/* Since the getJsonData function is asynchronous, We set an interval to see that it's done before we go on. */
		var checkLoadedJson = setInterval(function () {
			if (isLoadedData) {
				exhaustList(param);
				clearInterval(checkLoadedJson);
			}
		},50);

		$('close').onclick = function() {
			hide('popUp');
			$('sayCheese').src = 'cheesePicnone.gif';
		}
		$('print').onclick = function() {window.print()};
		$('param').innerHTML = 'גבינה לפי מרקם';
	}

	if($('xCredit')) {
		$('xCredit').onclick = function() { hide('credit');}
	}
}

window.onload = init;