var mainImg = new Image();
var flipped = new Array();

function checkEmail(obj) {
  var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
  var test = regex.test(obj.value);

  if (!test) {
	alert('Address is not a valid email address!');
  }

  return test;
}

function checkHTML(obj) {
  var regex = /[<>]/;
  var test = regex.test(obj.value);

  if (test) {
	alert('Please no HTML entities here!');
  }

  return !test;
}

function initImages(main, img0, img1, img2) {
	if (document.images) {
		if (main != '') {
			mainImg.src = main;
		}
		if (img0 != '') {
			flipped[0] = new Image();
			flipped[0].src = img0;
		}
		if (img1 != '') {
			flipped[1] = new Image();
			flipped[1].src = img1;
		}
		if (img2 != '') {
			flipped[2] = new Image();
			flipped[2].src = img2;
		}
	}
}

function removeWhiteSpaces(sInString) {
  sInString = sInString.replace( /\s+/g, "" );
  return sInString;
}


function over(num) {
  if(document.images && flipped[num] != null) {
    document.getElementById('mainImg').src = flipped[num].src;
  }
}
function out() {
  if(document.images) document.getElementById('mainImg').src = mainImg.src;
}

function imagesList() {
  window.open('images.php','s','toolbar=no,scrollbars=yes,resizable=1, height=600, width=600, left=20, top=20');
}


function popup(page)
{
  if (page != '')
    window.open('controller.php?page='+page,'s','toolbar=no,scrollbars=yes,height=400,width=510, left=20, top=20');
}

function print(id)
{
	if (id != null) {
		window.open('printProduct.php?product='+id,'s','toolbar=no,scrollbars=yes,height=500,width=680, left=20, top=20');
	}
}


function emailFriend(id)
{
	if (id != null) {
		window.open('emailFriend.php?p='+id,'s','toolbar=no,scrollbars=yes,height=400,width=400');
	}
}

function printOrder(id)
{
	window.open('printOrder.php?order=' + id,'s','toolbar=no,scrollbars=yes,height=700,width=700, left=20, top=20');
}

function printpage() {
	window.print();
}


function onoffForm(aForm, flag) {
  var aForm = document.getElementById(aForm);
	var regex = /^shipping/;
	for(i=0; i < aForm.elements.length; i++) {
		var name = aForm.elements[i].name;
		if (regex.test(name)) {
			aForm.elements[i].disabled = flag;
		}
	}
}

function enableShippingForm(aForm)
{
	var aForm = document.getElementById(aForm);
	var checked = aForm.useBilling.checked;
	var regex = /^shipping/;

	for(i=0; i < aForm.elements.length; i++) {
		var name = aForm.elements[i].name;
		if (regex.test(name)) {
			aForm.elements[i].value = aForm[name.replace(new RegExp("^shipping", "g"), "billing")].value;
			aForm.elements[i].disabled = checked;
		}
	}
}

function disableShippingForm(aForm)
{
	var aForm = document.getElementById(aForm);
	aForm.useBilling.checked = true;
	enableShippingForm(aForm);
}

function setFocus(aForm, aField) {
	aForm[aField].focus();
}

function isEmpty(aForm, aTextField) {
	if ((aForm[aTextField].value.length==0) ||
		(aForm[aTextField].value==null)) {
		return true;
	}
	else {
		return false;
	}
}

function compareFields(aForm, aTextField1, aTextField2) {
	if (document.forms[aForm][aTextField1].value ==	document.forms[aForm][aTextField2].value) {
		return true;
	}
	else {
		return false;
	}
}

function isEqual(aForm, aTextField, result) {
	if (document.forms[aForm][aTextField].value == result) {
		return true;
	}
	else {
		return false;
	}
}

function isChecked(aForm, aCheckBox) {
	return aForm[aCheckBox].checked;
}

function validateCheckout() {
  if (!document.forms['confirmData'].terms.checked) {
		alert ('If you wan\'t to order a product - you must agree with companies terms & conditions.');
		return false;
	}
	return true;
}

function howMany (formName, field) {
	var counter = 0;
	for (var i=0;i<document.forms[formName].length;i++) {
		if (current.name.indexOf(field) == 0) counter++;
	}
	return counter;
}

function validateRegistration() {
	var billingAndShipping = false;
	var checkedForm = "customerDetails";
	var passwd = removeWhiteSpaces(document.forms[checkedForm]["password"].value);

	if (isEmpty(checkedForm,"userName")) {
		setFocus(checkedForm,"userName");
		alert ("Login field cannot be empty!");
		return false;
	}
	if (isEmpty(checkedForm,"password")) {
		setFocus(checkedForm,"password");
		alert ("Password field cannot be empty!");
		return false;
	} else {
		document.forms[checkedForm]["password"].value = passwd;
		if (passwd.length < 6) {
			setFocus(checkedForm,"password");
			alert ("Password must have min. 6 signs without white spaces \n " +
					"(All white spaces will be deleted when saving password)!");
			document.forms[checkedForm]["password"].value = "";
			document.forms[checkedForm]["passwordRepeat"].value = "";
			return false;
		}
	}
	if (isEmpty(checkedForm,"passwordRepeat")) {
		setFocus(checkedForm,"passwordRepeat");
		alert ("Repeated password cannot be empty!");
		return false;
	}
	if (!compareFields(checkedForm,"password", "passwordRepeat")) {
		setFocus(checkedForm,"passwordRepeat");
		alert ("Password and repeated password don't match!");
		return false;
	}
	return	validateBilling("customerDetails") && validateShipping("customerDetails");
}


function validateReview () {
	var checkedForm = "addReview";

	if (isEmpty(checkedForm,"nickname") || isEqual(checkedForm, "nickname", "Enter your nickname here")) {
		setFocus(checkedForm,"nickname");
		alert ("\"Nickname\" is a required field ! Please enter all required fields.");
		return false;
	}

	if (isEmpty(checkedForm,"email") || isEqual(checkedForm, "email", "Enter your email here")) {
		setFocus(checkedForm,"email");
		alert ("\"Email\" is a required field ! Please enter all required fields.");
		return false;
	}

}

function validateContactForm () {
	var checkedForm = "contactForm";

	if (isEmpty(checkedForm,"conName") || isEqual(checkedForm, "conName", "Enter your name here")) {
		setFocus(checkedForm,"conName");
		alert ("\"Name\" is a required field ! Please enter all required fields.");
		return false;
	}

	if (isEmpty(checkedForm,"conEmail") || isEqual(checkedForm, "conEmail", "Enter your email here")) {
		setFocus(checkedForm,"conEmail");
		alert ("\"Email Address\" is a required field ! Please enter all required fields.");
		return false;
	}
}

function validateCallMe() {
	var checkedForm = "callme";
	var msg = " is a required field ! Please enter all required fields.";

	if (isEmpty(checkedForm,"name")) {
		setFocus(checkedForm,"name");
		alert ("\"Name\"" + msg);
		return false;
	}

	if (isEmpty(checkedForm,"contactNr")) {
		setFocus(checkedForm,"contactNr");
		alert ("\"contactNr\"" + msg);
		return false;
	}

	if (isEmpty(checkedForm,"postCode")) {
		setFocus(checkedForm,"postCode");
		alert ("\"postCode\"" + msg);
		return false;
	}

	return true;
}

function validateEmailAFriend(aForm) {

	if (isEmpty(aForm,"email")) {
		setFocus(aForm,"email");
		alert ("\"Email\" is a required field. Please enter all required fields!");
		return false;
	}
	if (isEmpty(aForm,"mailFrom")) {
		setFocus(aForm,"mailFrom");
		alert ("\"Mail from\" is a required field. Please enter all required fields!");
		return false;
	}

	return true;
}

function getURLParam(strUrl, strParamName){
  var strHref = window.location.href;
  if (strUrl != '')
  	strHref = strUrl;
  var strReturn = "";
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?"));
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = escape(aParam[1]);
        break;
      }
    }
  }
  return unescape(strReturn);
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


function filterNavigation(obj, order)
{
	var category = getURLParam('', 'category');
	var brand = getURLParam('', 'brand');
	var newCriteria = getURLParam('', 'new');
	var newURL = 'showSubcategory.php?';
        var term = getURLParam('', 'term');

	if (window.location.href.search(/searchResults\.php/) != -1)
		newURL = 'searchResults.php?';
	if (window.location.href.search(/specialOffers\.php/) != -1)
		newURL = 'specialOffers.php?';

	/*if (obj != null) {
		startIdx = getURLParam(obj.href, 'start_index');
		if (startIdx != '')
			newURL += 'start_index='+startIdx+'&';
	}*/
	if (obj != null)
	    newURL += 'start_index='+obj.value+'&';
	else
	    newURL += 'start_index='+$('pageNr').value+'&';

	if (newCriteria != '')
	    newURL += 'new='+newCriteria+'&';

	if (term != '')
	    newURL += 'term='+term+'&'+'search_by_term=search_by_term&';

	if (category != '')
		newURL += 'category='+category+'&';

	if (brand != '')
		newURL += 'brand='+brand+'&';

	if (order != null)
		newURL += 'sort_by_price='+order+'&';

	if ($('perPage').selectedIndex != -1 && $('perPage').value != -1)
		newURL += 'per_page='+$('perPage').value+'&';

	if ($('finishings') != null && $('finishings').selectedIndex != -1 && $('finishings').value != -1)
		newURL += 'finishing='+$('finishings').value+'&';

	window.location.href= rtrim(newURL, '&');
	return false;
}

function switchCategories(level) {

	for( var i=5; i>level; i--) {
		if (i != level)
			$('lvl'+i).selectedIndex = 0;
	}

	return $('categorySwitch').submit();
}

function switchImage(img, title) {
  /*var options = {method: 'get',
                 parameters: 'setId='+id,
                 onSuccess: function(transport) {
                    var doc = transport.responseXML;
                    var imgsrc = doc.getElementsByTagName('link')[0].firstChild.nodeValue;
                    var altText = doc.getElementsByTagName('alt')[0].firstChild.nodeValue;

                    if (imgsrc != '')
                      Tip('<img src=\''+imgsrc+'\' alt=\''+altText+'\' width=\'407\' />', BGCOLOR, '#FFF');
                    //$('producer_logo').setAttribute("src", doc.getElementsByTagName('link')[0].firstChild.nodeValue);
                    //$('producer_logo').setAttribute("alt", doc.getElementsByTagName('alt')[0].firstChild.nodeValue);
                  }
                };
  new Ajax.Request('imageGet.php', options);
  */
  if (img != '')
    Tip('<img src=\''+img+'\' alt=\''+title+'\' width=\'407\' />', BGCOLOR, '#FFF');
}

function goDetails(product, category) {
  if (category != null)
    window.location.href='showProduct.php?product='+product+'&category='+category;
  else
    window.location.href='showProduct.php?product='+product;
}

//function MM_jumpMenu(targ,selObj,restore){ //v3.0
//  eval(targ+".location='"+selObj.value+"'");
//  if (restore) selObj.selectedIndex=0;
//}
