var mainImg = new Image();
var flipped = new Array();
		
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.images['main_img'].src = flipped[num].src;
  }
}
function out() {
  if(document.images) document.images['main_img'].src = mainImg.src;
}

function print(id)
{
	if (id != null) {
		window.open('printProduct.php?product='+id,'s','toolbar=no,scrollbars=yes,height=700,width=500, left=20, top=20');
	}
}

function emailFriend(id)
{
	if (id != null) {
		window.open('emailFriend.php?product='+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=800,width=800, left=20, top=20');
}

function printpage() {
	window.print();  
}

function setFocus(aForm, aField) {
	document.forms[aForm][aField].focus();
}

function isEmpty(aForm, aTextField) {
	if ((document.forms[aForm][aTextField].value.length==0) ||
		(document.forms[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 document.forms[aForm].aCheckBox.checked;
}

function validateCheckout() {
	var radioChecked = false;
	for(counter = 0; counter < document.forms['confirmData'].payment.length; counter++) {
		if (document.forms['confirmData'].payment[counter].checked) {
      		radioChecked = true;
    	}
  	}
  
	if (!radioChecked) {
		alert ('Please choose payment type.');
		return false;
	}	
  	
  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;
}

//set of required fields for billing data form
function validateBilling(formid) {
	var checkedForm;
	var status = true;
	var msg = "Please fill required billing information fields(*)\n\n";
	
	checkedForm = document.getElementById(formid);
	
	if (isEmpty(checkedForm,"billingFName")) {
		setFocus(checkedForm,"billingFName");
		status = false;
		msg = msg + " First name,\n";
	}
  
	if (isEmpty(checkedForm,"billingLName")) {
		setFocus(checkedForm,"billingLName");
		status = false;
		msg = msg + " Last name,\n";
	}  	

	if (isEmpty(checkedForm,"billingMainAddress")) {
		setFocus(checkedForm,"billingMainAddress");
		status = false;
		msg = msg + "  Address,\n";
	}

	if (isEmpty(checkedForm,"billingPostalCode")) {
		setFocus(checkedForm,"billingPostalCode");
		status = false;
		msg = msg + "  Postal code,\n";		
	}
	
	if (isEmpty(checkedForm,"billingTown")) {
		setFocus(checkedForm,"billingTown");
		status = false;
		msg = msg + "  Town/City,\n";		
	}	
	
	if (isEmpty(checkedForm,"billingPhone")) {
		setFocus(checkedForm,"billingPhone");
		status = false;
		msg = msg + "  Phone number,\n";		
	}	
	
	if (isEmpty(checkedForm,"billingEmail")) {
		setFocus(checkedForm,"billingEmail");
		status = false;
		msg = msg + "  Email Address\n";		
	}	

	if (status) {
		return true;
	} else	{
		alert (msg);
		return false;
	}
		
}

function validateShipping(aForm) {
	var checkedForm = "shippingDetails";
	var status = true;
	var msg = "Please fill required shipping information fields(*)\n\n";

	if (aForm == "") checkedForm = "shippingDetails";
	else checkedForm = aForm;


	if (!isChecked(checkedForm,"useBilling")) {
		//if (isEmpty(checkedForm,"shippingName")) {
		//	setFocus(checkedForm,"shippingName");
		//	status = false;
		//	msg = msg + "  Name,\n";
		//}
		
		if (isEmpty(checkedForm,"shippingFName")) {
			setFocus(checkedForm,"shippingFName");
			status = false;
			msg = msg + " First name,\n";
		}
    
		if (isEmpty(checkedForm,"shippingLName")) {
			setFocus(checkedForm,"shippingLName");
			status = false;
			msg = msg + " Last name,\n";
		}    		
	
		if (isEmpty(checkedForm,"shippingMainAddress")) {
			setFocus(checkedForm,"shippingMainAddress");
			status = false;
			msg = msg + "  Address,\n";
		}
	
		if (isEmpty(checkedForm,"shippingPostalCode")) {
			setFocus(checkedForm,"shippingPostalCode");
			status = false;
			msg = msg + "  Postal code,\n";		
		}

		if (isEmpty(checkedForm,"shippingTown")) {
			setFocus(checkedForm,"shippingTown");
			status = false;
			msg = msg + "  Town/City,\n";		
		}
		
		if (isEmpty(checkedForm,"shippingPhone")) {
			setFocus(checkedForm,"shippingPhone");
			status = false;
			msg = msg + "  Phone number,\n";		
		}	
		
		if (isEmpty(checkedForm,"shippingEmail")) {
			setFocus(checkedForm,"shippingEmail");
			status = false;
			msg = msg + "  Email Address\n";		
		}	
	}
	
	if (status) {
		return true;
	} else	{
		alert (msg);
		return false;
	}
		
}
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;
}	
	
//set of requirements for product data form
function validateProduct(aForm) {
	var checkedForm = aForm;
	var status = true;
	var msg = " field must not be empty!";

	if (isEqual(checkedForm, 'prodSubcategory', -1)) {
		alert('Subcategory must be selected !');
		return false;
	}
	if (isEmpty(checkedForm,"prodBrand")) {
		setFocus(checkedForm,"prodBrand");
		alert ("\"Brand\"" + msg);
		return false;
	}	
	if (isEmpty(checkedForm,"prodModel")) {
		setFocus(checkedForm,"prodModel");
		alert ("\"Model\"" + msg);
		return false;
	}	
	if (isEmpty(checkedForm,"prodStockCode")) {
		setFocus(checkedForm,"prodStockCode");
		alert ("\"Stock Code\"" + msg);
		return false;
	}		
	if (isEmpty(checkedForm,"prodStdPrice")) {
		setFocus(checkedForm,"prodStdPrice");
		alert ("\"Product price\"" + msg);
		return false;
	}	
	
	return true;
}


function validateEmailAFriend() {
	var checkedForm =  "emailFriend";

	if (isEmpty(checkedForm,"email")) {
		setFocus(checkedForm,"email");
		alert ("\"Email\" is a required field. Please enter all required fields!");
		return false;
	}	
	if (isEmpty(checkedForm,"mailFrom")) {
		setFocus(checkedForm,"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("?")).toLowerCase();
    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 = 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){
	var size = document.filters.size;
	var type=document.filters.type;
	var order=document.filters.orderBy;
	var productsPerPage=document.filters.perPage;
	var category = getURLParam('', 'category');
	var brand = getURLParam('', 'brand');
	var newURL = 'showSubcategory.php?';
	
	if (obj != null) {
		startIdx = getURLParam(obj.href, 'products_start_index');
		if (startIdx != '')
			newURL += 'products_start_index='+startIdx+'&';
	}
	if (category != '')
		newURL += 'category='+category+'&';
		
	if (brand != '')
		newURL += 'brand='+brand+'&';
		
	if (order.selectedIndex != -1 && order.options[order.selectedIndex].value != -1)
		newURL += 'sort_by_price='+order.options[order.selectedIndex].value+'&';

	if (productsPerPage.selectedIndex != -1 && 
		productsPerPage.options[productsPerPage.selectedIndex].value != -1)
		newURL += 'products_per_page='+productsPerPage.options[productsPerPage.selectedIndex].value+'&';	
	if (size != null && size.selectedIndex != -1 && size.options[size.selectedIndex].value != -1)
		newURL += 'size='+size.options[size.selectedIndex].value+'&';
		
	if (type != null && type.selectedIndex != -1 && type.options[type.selectedIndex].value != -1)
		newURL += 'type='+type.options[type.selectedIndex].value+'&';
			
	window.location.href= rtrim(newURL, '&');
	return false;
}


function findPosX(obj) {
    var curleft = obj.offset().left;
    obj.parents().each(function(){
        curleft += $(this).offset().left;
    })
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop+=obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.y) {
        curtop+=obj.y;
    }
    return curtop;
}
