

// equal heights modified works on class element

function equalHeights(className) {
	var currentTallest = 0;
	jQuery('.' + className).each(function() {
		if (jQuery(this).height() > currentTallest) 
			currentTallest = jQuery(this).height();
	});
	
	jQuery('.' + className).height(currentTallest);
}

jQuery.fn.equalHeights = function(px) {
	jQuery(this).each(function(){
		var currentTallest = 0;
		jQuery(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = jQuery(this).height(); }
		});
		if (!px || !Number.prototype.pxToEm) 
			currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if (jQuery.browser.msie && jQuery.browser.version == 6.0) { jQuery(this).children().css({'height': currentTallest}); }
		jQuery(this).children().css({'min-height': currentTallest}); 
	});
	return this;
};

// PX to EM

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: false
	}, settings);
	
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};	
	
	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
		to get an accurate em value. */
				
	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){		
			return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
			
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};

// Minimum height checker for catalog landing pages!
function catLandingMinHeight() {
	var minHeight = $("#problemYesProblemNo").height() + 160;

	if ($(".catLanding").height() < minHeight)
		$(".catLanding").height(minHeight);

	if ($(".ezineLanding").height() < minHeight)
		$(".ezineLanding").height(minHeight);

}

$(window).load(function() {
	catLandingMinHeight();
});

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function ElementClearDefaultValue(id, value, def_value, color){
	if(value == def_value){
		document.getElementById(id).value = '';
		document.getElementById(id).style.color = color;
	}
}

function ElementFillDefaultValue(id, value, def_value, color){
    if (value == '') {
        document.getElementById(id).value = def_value;
        document.getElementById(id).style.color = color;
    }
}

function changeProductContent(pid, c, referrer, content_type)
{
    //trackPageView(window.location+'&nav=' + content_type);
    var randomNumber = Math.floor(Math.random() * 101);
    url = 'inc_product_description_ajax.asp?pid=' + pid + '&c=' + c + '&referrer=' + referrer + '&content_type=' + content_type + '&rand=' + randomNumber;
	 if (checkIfCADomainJS() == 0)
		url = 'http://' + document.domain + '/' + url

    ajaxpage(url, 'mainProductDesc');
}

var bustcachevar=0 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function ajaxpage(url, containerid){
	var page_request = false
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
			}
		}
	else
		return false
	
	page_request.onreadystatechange=function(){
		loadpage(page_request, containerid)
	}
	
	if (bustcachevar) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
}

function loadpage(page_request, containerid){
    if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) {
		
		if ( document.getElementById(containerid) != null){
		    document.getElementById(containerid).innerHTML = page_request.responseText;

            /*
		    //stock code, just an idea
		    var parent = $('#' + containerid).closest('.mainProdCartWrapper');

		    if (parent.length == 0) {
		        parent = $('#' + containerid).closest('.mainCatProductBuy');
		    }

		    if (parent.length == 0) {
		        parent = $('#' + containerid).closest('.bottomProdCartWrapper');
		    }

		    if (parent.length == 0) {
		        parent = $('#' + containerid).closest('.bottomProdCartWrapper_v2');
		    }

		    if (parent.length == 0) {
		        parent = $('#' + containerid).closest('.crossCartWrapper');
		    }

		    if (parent.length == 0) {
		        parent = $('#' + containerid).closest('.topProdCartWrapper');
		    }

		    if (parent.length == 0) {
		        parent = $('#' + containerid).closest('.bottomProdCartWrapper_v2');
		    }

		    if ($('#' + containerid).children('#option_stock').length != 0) {
		        if (parseInt(($('#' + containerid).children('#stock_active')).html()) == 1) {
                    $($(parent).children('.dropdowns').children('.quantWrapper').children('.stock')).show();

		            if (parseInt($($('#' + containerid).children('#option_stock')).html()) > 0) {
		                $(parent).children('.dropdowns').children('.quantWrapper').children('.stock').children('tbody').children('tr').children('td.off').removeClass('active');
		                $(parent).children('.dropdowns').children('.quantWrapper').children('.stock').children('tbody').children('tr').children('td.on').addClass('active');
		            }
		            else {
		                $(parent).children('.dropdowns').children('.quantWrapper').children('.stock').children('tbody').children('tr').children('td.on').removeClass('active');
		                $(parent).children('.dropdowns').children('.quantWrapper').children('.stock').children('tbody').children('tr').children('td.off').addClass('active');
		            }
		        }
		        else {
		            $($(parent).children('.dropdowns').children('.quantWrapper').children('.stock')).hide();
                }
            }
            */

        	tb_init('a.thickbox, area.thickbox, input.thickbox, div.thickbox');//DON'T REMOVE THIS! Thickbox duplication is fixed in thickboxJS.asp script
		}
    }
}

function open_popup(theURL) { //v2.0
 MM_openBrWindow(theURL,'','scrollbars=yes,resizable=yes,width=520,height=500');
}

jQuery('.mainCatalogList .sort .table a, .mainCatalogList .sort .row a, .mainCatalogList .sort .cel a').live('click', function () {
    var oldListClass;

    if (jQuery(this).closest('tr').children('td.active').hasClass('table'))
        oldListClass = 'mainCatTableList';
    else if (jQuery(this).closest('tr').children('td.active').hasClass('row'))
        oldListClass = 'mainCatRowList';
        
    else if (jQuery(this).closest('tr').children('td.active').hasClass('cel'))
        oldListClass = 'mainCatCelList';

    jQuery(this).closest('tr').children('td.active').removeClass('active');
    jQuery(this).closest('td').addClass('active');

    var currentListClass;

    if (jQuery(this).closest('tr').children('td.active').hasClass('table')) {
        currentListClass = 'mainCatTableList';
        SaveSession("CatalogPageView", "table");
        _gaq.push(['_trackPageview', '/TabView']);
    }
    else if (jQuery(this).closest('tr').children('td.active').hasClass('row')) {
        currentListClass = 'mainCatRowList';
        SaveSession("CatalogPageView", "row");
        _gaq.push(['_trackPageview', '/RowView']);
    }
    else if (jQuery(this).closest('tr').children('td.active').hasClass('cel')) {
        currentListClass = 'mainCatCelList';
        SaveSession("CatalogPageView", "cel");
    }

    var div = jQuery('div.' + oldListClass);
    div.removeClass(oldListClass);
    div.addClass(currentListClass);

    return false;
})

//ajax version - old
jQuery('.contentTabs ul.tabNav li a').live('click', function () {
    var activeLink = this;
    jQuery(this).closest('ul.tabNav').children('li').children('a.active').removeClass('active');
    jQuery(this).addClass('active');
})

//reset all filters
/*
jQuery('.filter .reset a').live('click', function () {
    jQuery(this).closest('.filter ').children('tbody').children('tr').children('td').children('select').val('-');
    return false;
})
*/

function Show(id){
	if (document.getElementById(id) != null) document.getElementById(id).style.display="";
}

function Hide(id){
	if (document.getElementById(id) != null) document.getElementById(id).style.display="none";
}

//-- VALIDATION FUNCTIONS --
function isValidEmail(fld) {
   
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\&\=\#\;\:\\\"\[\]]/ ;
    var error_mail = false;
    $(fld).removeClass('inputboxerror');
  
    if ($(fld).val() == "") {
        error_mail = true;
        $(fld).addClass('inputboxerror');
    } else if (!emailFilter.test($(fld).val())) { 
        error_mail = true;
        $(fld).addClass('inputboxerror');
    } else if ($(fld).val().match(illegalChars)) {
        error_mail = true;
        $(fld).addClass('inputboxerror'); 
    } else {
        error_mail = false;
        $(fld).removeClass('inputboxerror');
    }
    return error_mail;
}

function ValidatePhoneNumberDropdown(field, childField) {
    var error = false;
    $(field).removeClass('inputboxerror');
    $(childField).removeClass('inputboxerror');
    var GoodChars = "0123456789.()-+/ ";
    var fieldValue = $(field).val();

    for (i = 0; i <= fieldValue.length - 1; i++) {
        if (GoodChars.indexOf(fieldValue.charAt(i)) == -1) {
            error = true;
        }

        samCifre = fieldValue.replace(/[\(\)\.\-\+\/\ ]/g, '');
    }

    if (($(field).val() == "") && ($(childField).val().length > 4) && !error) {
        error = false;
    }
    else if (($(field).val().length > 4) && (!error)) {
        error = false;
    }
    else {
        error = true;
        $(field).addClass('inputboxerror');
        $(childField).addClass('inputboxerror');
    }

    return error;
}

function checkPhoneNumber(nbr, lang) {
    var valid = true
    var GoodChars = "0123456789.()-+/ "
    var i = 0
    var samCifre = 0;

    if (nbr == "") {
        // Return false if number is empty
        valid = false
    }

    for (i = 0; i <= nbr.length - 1; i++) {
        if (GoodChars.indexOf(nbr.charAt(i)) == -1) {
            valid = false
        } // End if statement

        samCifre = nbr.replace(/[\(\)\.\-\+\/\ ]/g, '');

    } // End for loop

    if (lang == 'SI') {

        if ((samCifre.length == 13 && samCifre.substring(0, 5) == "00386") || (samCifre.length == 11 && samCifre.substring(0, 3) == "386") || (samCifre.length == 9 && samCifre.substring(0, 1) == 0)) {
            valid = true;
        }
        else {
            valid = false;
        }
    }
    return valid
}

//showErr, idDivErr, idDiv
function IsNumberValid(fld, Min, Max) {
    $(fld).removeClass('inputboxerror');
    var valid = true;
    if ($(fld).val() == "") {
        valid = false;
        $(fld).addClass('inputboxerror');
    }
    else if (isNaN($(fld).val())) {
        valid = false;
        $(fld).addClass('inputboxerror');
    }
    else if ($(fld).val() < Min || $(fld).val() > Max) {
        valid = false;
        $(fld).addClass('inputboxerror');
    }
    
    return valid;
}

//showErr, idDiv, idDivErr
function IsStringValid(fld, minStringLength) {

    var illegalChars = /[a-zA-Z0-9 ]+$/; // allow letters, numbers, and underscores
    var length = minStringLength;
    var valid = true;
    $(fld).removeClass('inputboxerror');

    //if (($(fld).val().length < length) || ($(fld).val().length == 0)) {
    if ($(fld).val().length == 0) {
        valid = false;
        $(fld).addClass('inputboxerror');
    }

    return valid;
}

function IsSelectionBoxValid(id) {
    var valid = false;

    if (document.getElementById(id) != null) {
        var region_inx = document.getElementById(id).selectedIndex;

        if (document.getElementById(id).options[region_inx].value == '') {
            document.getElementById(id).setAttribute('class', 'inputboxerror');
            valid = false;
        }
        else {
            document.getElementById(id).setAttribute('class', '');
            valid = true;
        }
    }
    return valid;
}

function IsSelectionValid(fld) {
    var valid = true;
    $(fld).removeClass('inputboxerror');

    if ($(fld).val() == 0) {
        valid = false;
        $(fld).addClass('inputboxerror');
    }

    return valid;
}

function IsPhoneNumberValid(fld, lang) {
    var valid = true;
    var GoodChars = "0123456789.()-+/ ";
    var i = 0;
    var samCifre = 0;
    $(fld).removeClass('inputboxerror');

    if ($(fld).val() == "") {
        // Return false if number is empty
        valid = false;
        $(fld).addClass('inputboxerror');
    }

    for (i = 0; i <= $(fld).val().length - 1; i++) {
        if (GoodChars.indexOf($(fld).val().charAt(i)) == -1) {
            valid = false;
            $(fld).addClass('inputboxerror');
        } // End if statement

        samCifre = $(fld).val().replace(/[\(\)\.\-\+\/\ ]/g, '');

    } // End for loop

    if (lang == 'SI') {
        if ((samCifre.length == 13 && samCifre.substring(0, 5) == "00386") || (samCifre.length == 11 && samCifre.substring(0, 3) == "386") || (samCifre.length == 9 && samCifre.substring(0, 1) == 0)) {
            valid = true;
            $(fld).removeClass('inputboxerror');
        }
        else {
            valid = false;
            $(fld).addClass('inputboxerror');
        }
    }
    return valid;
}

function IsCommentBoxValid(s) {
    var re = new RegExp('\<\s*.*\s*>');
    var m = re.exec(s);
    if (m == null) {
        return false;
    } else {
        return true;
    }
}



//-- END OF VALIDATE FUNCTIONS --

function resetControlList(controlList) {
    for (i = 0; i < controlList.length; i++) {
        $(controlList[i]).removeClass('inputboxerror');    
    }
}

function resetParentControlList(controlList) {
    for (i = 0; i < controlList.length; i++) {
        $(controlList[i]).closest('div').removeClass('inputboxerror');
    }
}

function submitFormIfValid(formName, lang) {

    var isError = false;
    var inputs = $("#" + formName + " :input");
    var checkboxes = $("#" + formName + " :checkbox");

    resetControlList(inputs);
    resetParentControlList(checkboxes);

    for (i = 0; i < inputs.length; i++) {
        if ($(inputs[i]).attr('rel') == 'o' && ($(inputs[i]).val() == '' || ($(inputs[i]).val() == 0 && !(lang == 'LV' || lang == 'LVRU')) || $(inputs[i]).val() == '-' || $(inputs[i]).val() == -1)) {
            isError = true;
            $(inputs[i]).addClass('inputboxerror');
        }
        else if ($(inputs[i]).attr('name') == "email" && $(inputs[i]).attr('rel') == 'o' && isValidEmail($(inputs[i]))) {
            isError = true;
            $(inputs[i]).addClass('inputboxerror');
        }
        else if ($(inputs[i]).attr('name') == "phone" && $(inputs[i]).attr('rel') == 'o' && !checkPhoneNumber($(inputs[i]).val(), lang)) {
            isError = true;
            $(inputs[i]).addClass('inputboxerror');
        }
    }

    for (i = 0; i < checkboxes.length; i++) {
        if (!$(checkboxes[i]).attr('checked') && $(checkboxes[i]).attr('rel') == 'o') {
            isError = true;
            $(checkboxes[i]).closest('div').addClass('inputboxerror');
        }
    }

    if (lang == 'SI') {
        var mob = document.getElementById('mob');
        var tel = document.getElementById('tel');
        var GoodChars = "0123456789.()-+/ ";

        if ((mob != null) && (tel != null)) {
            if ((mob.value.length < 5) && (tel.value.length < 5)) {
                isError = true;
                mob.setAttribute("class", "inputboxerror");
                tel.setAttribute("class", "inputboxerror");
            }

            for (i = 0; i <= mob.value.length - 1; i++) {
                if (GoodChars.indexOf(mob.value.charAt(i)) == -1) {
                    isError = true;
                    mob.setAttribute("class", "inputboxerror");
                    tel.setAttribute("class", "inputboxerror");
                }
            }

            for (i = 0; i <= tel.value.length - 1; i++) {
                if (GoodChars.indexOf(tel.value.charAt(i)) == -1) {
                    isError = true;
                    mob.setAttribute("class", "inputboxerror");
                    tel.setAttribute("class", "inputboxerror");
                }
            }
        }
    }

    if (document.getElementById('region') != null) {
        var region_inx = document.getElementById('region').selectedIndex;

        if (region_inx != null) {
            if (document.getElementById('region').options[region_inx].value == '') {
                document.getElementById('region').setAttribute('class', 'inputboxerror');
                isError = true;
            }
            else {
                document.getElementById('region').setAttribute('class', '');
            }
        }
    }

    if (document.getElementById('postOffice') != null) {
        var post_inx = document.getElementById('postOffice').selectedIndex;

        if (post_inx != null) {
            if (document.getElementById('postOffice').options[post_inx].value == '') {
                document.getElementById('postOffice').setAttribute('class', 'inputboxerror');
                isError = true;
            }
            else {
                document.getElementById('postOffice').setAttribute('class', '');
            }
        }
    }

    if (!isError) {
        setCookie('subscribed', 'true', 365);
        $('#' + formName).closest('div').children('.error').hide();
        jQuery(document.forms[formName]).submit();
    }
    else {
        $('#' + formName).closest('div').children('.error').show();
    }
}


//function for main price set up on site
var ProductPrice=[];
function SetPrice(id, val) {
	
var normalselect = document.getElementById('select_menu' + id);
var v2Select = document.getElementById('v2select_menu' + id);
var savePrice = ProductPrice[val]["you_save"];

//v1 prices
	if (document.getElementById('yourPriceWhole' + id) != null) {
		document.getElementById('yourPrice' + id).innerHTML = ProductPrice[val]["your_price"];
		if (ProductPrice[val]["your_price"] == '')
			Hide('yourPriceWhole' + id);
		else 
			Show('yourPriceWhole' + id);
    };
	
	
	if (savePrice == '')
	{
		if (document.getElementById('regulaPriceWhole' + id) != null) {
			document.getElementById('regulaPriceWhole' + id).className = 'yourPrice';
		}
	}
	else
	{
		if (document.getElementById('regulaPriceWhole' + id) != null) {
			document.getElementById('regulaPriceWhole' + id).className = 'regPrice';
		}
	}
	
	

	if (document.getElementById('savePriceWhole' + id) != null)
		document.getElementById('savePrice' + id).innerHTML = ProductPrice[val]["you_save"];

	if (document.getElementById('savePriceWhole' + id) != null) {
		if (ProductPrice[val]["you_save"] == '')
			Hide('savePriceWhole' + id);
		else 
			Show('savePriceWhole' + id);
	}

	if (document.getElementById('regulaPriceWhole' + id) != null) {
	
		document.getElementById('regulaPrice' + id).innerHTML = ProductPrice[val]["reg_price"];
		if (ProductPrice[val]["reg_price"] == '')
			Hide('regulaPriceWhole' + id);
		else
			Show('regulaPriceWhole' + id);
	};

	if (document.getElementById('installPriceWhole' + id) != null)
		document.getElementById('installPrice' + id).innerHTML = ProductPrice[val]["min_install"];
    
	if (document.getElementById('installPriceWhole' + id) != null) {
		if (ProductPrice[val]["min_install"] == '')
			Hide('installPriceWhole' + id);
		else 
			Show('installPriceWhole' + id);
	}
	
	//v2 prices
	if (document.getElementById('v2yourPriceWhole' + id) != null) {
		document.getElementById('v2yourPrice' + id).innerHTML = ProductPrice[val]["your_price"];
		if (ProductPrice[val]["your_price"] == '')
			Hide('v2yourPriceWhole' + id);
		else 
			Show('v2yourPriceWhole' + id);
    };

	if (savePrice == '')
	{
		if (document.getElementById('v2regulaPriceWhole' + id) != null) {
			document.getElementById('v2regulaPriceWhole' + id).className = 'yourPrice';
		}
	}
	else
	{
		if (document.getElementById('v2regulaPriceWhole' + id) != null) {
			document.getElementById('v2regulaPriceWhole' + id).className = 'regPrice';
		}
	}
	
	
	if (document.getElementById('v2savePriceWhole' + id) != null)
		document.getElementById('v2savePrice' + id).innerHTML = ProductPrice[val]["you_save"];

	if (document.getElementById('v2savePriceWhole' + id) != null) {
		if (ProductPrice[val]["you_save"] == '')
			Hide('v2savePriceWhole' + id);
		else 
			Show('v2savePriceWhole' + id);
	}

	if (document.getElementById('v2regulaPriceWhole' + id) != null) {
		document.getElementById('v2regulaPrice' + id).innerHTML = ProductPrice[val]["reg_price"];
		if (ProductPrice[val]["reg_price"] == '')
			Hide('v2regulaPriceWhole' + id);
		else
			Show('v2regulaPriceWhole' + id);
	};

	if (document.getElementById('v2installPriceWhole' + id) != null)
		document.getElementById('v2installPrice' + id).innerHTML = ProductPrice[val]["min_install"];
    
	if (document.getElementById('v2installPriceWhole' + id) != null) {
		if (ProductPrice[val]["min_install"] == '')
			Hide('v2installPriceWhole' + id);
		else 
			Show('v2installPriceWhole' + id);
	}
	
	if (normalselect != null) {
		 for(index = 0; index < normalselect.length; index++) {
			 
   				if(normalselect[index].value == val) {
					 normalselect.selectedIndex = index;}}
	}
		
		
	if (v2Select != null) {
		 for(index = 0; index < v2Select.length; index++) {
   				if(v2Select[index].value == val) {
					 v2Select.selectedIndex = index;}}
	}
	

	
		
}

function setQuantity(id, val)
{
var normalQ = document.getElementById('quantity' + id);
var v2Q= document.getElementById('v2quantity' + id);

	if (normalQ != null) {
		 for(index = 0; index < normalQ.length; index++) {
			 
   				if(normalQ[index].value == val) {
					 normalQ.selectedIndex = index;}}
	}
		
		
	if (v2Q != null) {
		 for(index = 0; index < v2Q.length; index++) {
   				if(v2Q[index].value == val) {
					 v2Q.selectedIndex = index;}}
	}
	
}

function SetPriceQuantity (pid, divChange, diferencVar, tn){
	
	var opid = 0;
	var opidDD = document.getElementById('select_menu' + pid);
	var opidDDv2 = document.getElementById('v2select_menu' + pid);
	var _thisOpid;
	var inxOpid = 0;
	
	var q = 1;
	var qDD = document.getElementById('quantity' + pid);
	var _thisQ;
	var inxQ = 0;
	var path_sep = '/';
	
	var sLink='';
	
	
	if (diferencVar == "v2")
	{
		if (opidDDv2 != null){
			_thisOpid = opidDDv2;
			inxOpid = _thisOpid.selectedIndex;
			opid = _thisOpid.options[inxOpid].value;
		}
		
		if (opidDD != null) {
		 for(index = 0; index < opidDD.length; index++) {
   				if(opidDD[index].value == opid) {
					 opidDD.selectedIndex = index;}}
		}
	}
   	else
   	{
		if (opidDD != null){
			_thisOpid = opidDD;
			inxOpid = _thisOpid.selectedIndex;
			opid = _thisOpid.options[inxOpid].value;
		}
		
		if (opidDDv2 != null) {
		 for(index = 0; index < opidDDv2.length; index++) {
   				if(opidDDv2[index].value == opid) {
					 opidDDv2.selectedIndex = index;}}
		}
   	}
	
	if (qDD != null){
		_thisQ = qDD;
		inxQ = _thisQ.selectedIndex;
		q = _thisQ.options[inxQ].value;
    }

    sLink = 'ajax_product_prices.asp?pid=' + pid + '&opid=' + opid + '&q=' + q + '&diferencVar=&tn=' + tn+ '&nocache=' + Math.random();
	
	 if (checkIfCADomainJS() == 0){
		var sLink = path_sep + sLink;
	}

    ajaxpage(sLink, divChange + pid);

    sLink = 'ajax_product_prices.asp?pid=' + pid + '&opid=' + opid + '&q=' + q + '&diferencVar=v2&tn=' + tn+ '&nocache=' + Math.random();
	
	 if (checkIfCADomainJS() == 0){
		var sLink = path_sep + sLink;
	}
	
	ajaxpage(sLink,'v2'+divChange+pid);
}

//Functions for CART
function addToCart(pid, ptype){
	var opid = 0;
	var opidDD = 'select_menu' + pid;
	var _thisOpid;
	var inxOpid = 0;
	
	var q = 1;
	var qDD = 'quantity' + pid;
	var _thisQ;
	var inxQ = 0;
	var path_sep = '/';
   
	if (document.getElementById(opidDD) != null){
		_thisOpid = document.getElementById(opidDD);
        inxOpid = _thisOpid.selectedIndex;
        opid = _thisOpid.options[inxOpid].value;
    }
	
	if (document.getElementById(qDD) != null){
		_thisQ = document.getElementById(qDD);
		inxQ = _thisQ.selectedIndex;
		q = _thisQ.options[inxQ].value;
    }
	
	var sLink = 'cart_add.asp?pid=' + pid + '&ptype=' + ptype + '&opid=' + opid + '&q=' + q;
	
	 if (checkIfCADomainJS() == 0){
		var sLink = path_sep + sLink;
	}
	
    document.location.href = sLink;
}

function addToCartRef(pid, ptype, refVariable) {
    var opid = 0;
    var opidDD = 'select_menu' + pid;
    var _thisOpid;
    var inxOpid = 0;

    var q = 1;
    var qDD = 'quantity' + pid;
    var _thisQ;
    var inxQ = 0;
    var path_sep = '/';

    if (document.getElementById(opidDD) != null) {
        _thisOpid = document.getElementById(opidDD);
        inxOpid = _thisOpid.selectedIndex;
        opid = _thisOpid.options[inxOpid].value;
    }

    if (document.getElementById(qDD) != null) {
        _thisQ = document.getElementById(qDD);
        inxQ = _thisQ.selectedIndex;
        q = _thisQ.options[inxQ].value;
    }
    var sLink = 'cart_add.asp?pid=' + pid + '&ptype=' + ptype + '&opid=' + opid + '&q=' + q + '&refVariable=' + refVariable;


     if (checkIfCADomainJS() == 0){
        var sLink = path_sep + sLink;
    }

    document.location.href = sLink;
}


function addToCartV2(pid, ptype, diferencVar) {
    var opid = 0;
    var opidDD = diferencVar + 'select_menu' + pid;
    var _thisOpid;
    var inxOpid = 0;

    var q = 1;
    var qDD = diferencVar + 'quantity' + pid;
    var _thisQ;
    var inxQ = 0;
    var path_sep = '/';
	

    if (document.getElementById(opidDD) != null) {
        _thisOpid = document.getElementById(opidDD);
        inxOpid = _thisOpid.selectedIndex;
        opid = _thisOpid.options[inxOpid].value;
    }

    if (document.getElementById(qDD) != null) {
        _thisQ = document.getElementById(qDD);
        inxQ = _thisQ.selectedIndex;
        q = _thisQ.options[inxQ].value;
    }

    var sLink = 'cart_add.asp?pid=' + pid + '&ptype=' + ptype + '&opid=' + opid + '&q=' + q;

     if (checkIfCADomainJS() == 0){
        var sLink = path_sep + sLink;
    }

    document.location.href = sLink;
}

function goToCart1(lang) {
    var sLink = "";

    if (lang == "RO") {
        var region = $('div.region').children('select').val();
        var postal = $('div.postal').children('select').val();

        sLink = "cart1.asp?postal=" + postal;
    }
    else {
        var paymentType = $("input[name='payment']:checked").attr('id');

        if (lang == "LT") {
            paymentType = $('div.personal_lt').children('select').val();
            if (paymentType == 'webtopay_shop') {
                if ($("input[name='shop']:checked").val() == undefined) {
                    $('#choose_value').show();
                    return;
                }
            }

        }

        sLink = "cart1.asp?payment_type=" + paymentType;

        if (paymentType == 'instal') {
            if (lang != "LT") {
                sLink += "&installment=" + $('div.installments').children('select').val();
            }
            else {
                sLink += "&installment=" + $('div.installments_lt').children('select').val();
            }
            //sLink += "&installment=" + $('div.installments').children('select').val();
        }
        else if (paymentType == 'ccard') {
            if (lang == "LT") {
                //var bank = $("input[name='cc']:checked").attr('id');
                sLink += "&bank=1&bank_installment=1";
            }
            else
                sLink += "&ccard=" + $('div.ccard').children('select').val();
        }
    }	
	
	if (document.getElementById("regularPrice")!=null)
	{sLink += "&regularPrice="+document.getElementById("regularPrice").value;}
	
	if (document.getElementById("discount")!=null)
	{sLink += "&discount="+document.getElementById("discount").value;}
	
	if (document.getElementById("discountCoupon")!=null)
	{sLink += "&discountCoupon="+document.getElementById("discountCoupon").value;}
	
	if (document.getElementById("yourPrice")!=null)
	{sLink += "&yourPrice="+document.getElementById("yourPrice").value;}
	
	if (document.getElementById("postage")!=null)
	{sLink += "&postage="+document.getElementById("postage").value;}

	if (document.getElementById("finalPrice")!=null)
	{sLink += "&finalPrice="+document.getElementById("finalPrice").value;}
	
	if (document.getElementById("installmentText")!=null)
	{sLink += "&installmentText="+document.getElementById("installmentText").value;}

	if (lang == "LT") {
	    if (document.getElementById("postage_temp") != null)
	    { sLink += "&postage_temp=" + document.getElementById("postage_temp").value; }

	    if (document.getElementById("finalPrice_temp") != null)
	    { sLink += "&finalPrice_temp=" + document.getElementById("finalPrice_temp").value; }
	}

	if (document.getElementsByName("payment")!=null) {
        if (lang != "LT") {
		    var paymentLength = document.getElementsByName("payment").length;
		    var paymentObj = document.getElementsByName("payment");
		    for(var i = 0; i < paymentLength; i++) {
		    if(paymentObj[i].checked) 
			    {sLink += "&payment="+paymentObj[i].value;}
		    }
        }
        else {
            var payment = $('div.personal_lt').children('select').val();
            if (payment == 'webtopay_shop') {
                if ($("input[name='shop']:checked").val() != undefined) {
                    sLink += "&shop=" + $("input[name='shop']:checked").val();
                }
                payment = 'webtopay';
            }
            sLink += "&payment=" + payment;
        }
	}
	
	if (document.getElementById("nbr_install")!=null)
	{sLink += "&nbr_install="+document.getElementById("nbr_install").value;}
	
	if (document.getElementById("nbr_install_ccard")!=null)
	{sLink += "&nbr_install_ccard=" + document.getElementById("nbr_install_ccard").value; }

	if (document.getElementById("collect") != null) {
	    if (document.getElementById("collect").checked == true) {
	        sLink += "&collect=" + document.getElementById("collect").value;
	    }
	}
    
    document.location.href=sLink;

}
function goToCart2() {
    var gender = $("input[name='sex']:checked").attr('id'); //m, f
    var firstName = $("input[name='name']").val();
    var lastName = $("input[name='surname']").val();
    var birthYear = $("select[name='year']").val();
    var birthMonth = $("select[name='month']").val();
    var birthDay = $("select[name='day']").val();
    var address1 = $("input[name='addressLine1']").val();
    var zip = $("input[name='zip']").val();
    var city = $("input[name='city']").val();
    var phone = $("input[name='phone']").val();
    var email = $("input[name='email']").val();
    var comments = $("textarea[name='comments']").val();

    SaveSession("gender", gender);
    SaveSession("name", firstName);
    SaveSession("surname", lastName);
    SaveSession("address", address1);
    SaveSession("zip", zip);
    SaveSession("city", city);
    SaveSession("phone", phone);
    SaveSession("email", email);
    SaveSession("comment", comments);

    jQuery(document.forms['frmCartOrderConfirm']).submit(); 
}

function editToggle1() {

    $('.installments > select').hide();
    $('.ccard > select').hide();
    $('.ccw').hide();
    $('.cartTotal').removeClass("instTotal");
    $('.cartCredOptionsR').hide();
}

function editToggle2() {

    $('.ccw').hide();
    $('.ccard > select').hide();
    $('.installments > select').show();
    $('.cartTotal').addClass("instTotal");
    $('.cartCredOptionsR').hide();
}

function editToggle3() {
    $('.installments > select').hide();
    $('.ccard > select').show();
    $('.cartTotal').removeClass("instTotal");
}

function editToggleLT() {

    $('.installments > select').hide();
    $('.ccw').show();
    $('.cartTotal').removeClass("instTotal");
    $('.cartCredOptionsR').show();
}

//END functions for CART

function searchFor(id, defaultText, event) {
	
	var url = '';
	
	 if (checkIfCADomainJS() == 0)
		url = 'http://' + document.domain + '/'
		
		
    if (event != null) {
        if (event.keyCode == 13) {
            var searchText = $('#' + id).val();

            if (searchText != defaultText) {
                var searchLink = url+"index.asp?tn=search&search=" + encodeURIComponent(searchText);
                document.location.href = searchLink;
            }
        }
    }
    else {
        var searchText = $('#' + id).val();

        if (searchText != defaultText) {
            var searchLink = url+"index.asp?tn=search&search=" + encodeURIComponent(searchText);
            document.location.href = searchLink;
        }
    }
}

//Lines

$(document).ready(function () {
    $('.mainNav > .dormeoType').click(function () {
        $('.dormeoTypeWin').slideDown('fast', function () {
            $('#typBtn').addClass("hidden");
            $('#typBtnT').addClass("hidden");
        });
    });

    $('.topSdw > .dormeoType').click(function () {
        $('.dormeoTypeWin').slideUp('fast', function () {
            $('#typBtn').removeClass("hidden");
            $('#typBtnT').removeClass("hidden");
        });
    });

    $('.mainNav > .dormeoTypeWin').hover(
        function () { },
        function () {
            $('.dormeoTypeWin').slideUp('fast', function () {
                $('#typBtn').removeClass('hidden'); $('#typBtnT').removeClass('hidden');
            });
        });

    $('.headerCarW').hover(
        function () { },
        function () {
            $('.headerCarW').slideUp('fast', function () {
            });
        });



});

// END Lines


// Header mini cart
function showHeadCart()
		{
        $('.headerCarW').slideDown('fast');
   		};


// END Header mini cart

function openCreditPopup(priceTotal, spec, payment)
{
	var url = '';
	var nbr_install = 0 ;
    var inx = 0;
	
	if (payment=='install')
	{
		if(document.getElementById('nbr_install')!=null){
        inx = document.getElementById('nbr_install').selectedIndex;
        nbr_install = document.getElementById('nbr_install').options[inx].value;}
	}
	if (payment=='ccard')
	{
		if(document.getElementById('nbr_install_ccard')!=null){
        inx = document.getElementById('nbr_install_ccard').selectedIndex;
        nbr_install = document.getElementById('nbr_install_ccard').options[inx].value;}
	}
    
	
	url = 'popup_credit.asp?height=380&width=540&payment='+payment+'&priceTotal='+priceTotal+'&spec='+spec+'&nbr_install='+nbr_install;
	
	
	//alert('popup_credit.asp?height=380&width=540&payment='+payment+'&priceTotal='+priceTotal+'&spec='+spec+'&nbr_install='+nbr_install);
	tb_show('', url, '');
}


function RefreshPrices_Ajax(tip) {

    if (document.getElementById('pcouponValue') != null) {
        document.getElementById('pcouponValue').style.display = "block";
    }

    url = 'engine_cart_coupon.asp?tip=' + tip;

    url += '&validate_coupon=1'

    if (document.getElementById('installmentText') != null) {
        url += "&installmentText=" + document.getElementById('installmentText').value;
    }

    if (document.getElementById('coupontext') != null) {
        url += "&coupontext=" + document.getElementById('coupontext').value.replace("%", "");
    }

    if (document.getElementById("collect") != null) {
        if (document.getElementById("collect").checked == true)
            url += "&collect=" + document.getElementById("collect").value;
        else
            url += "&collect=0";
    }

    if (checkIfCADomainJS() == 0)
        url = 'http://' + document.domain + '/' + url;
		
	 url += "&no_cache=" + Math.round((new Date().getTime() * Math.random()));

    ajaxpage(url, 'divIncCartTotals');
	

}

function RefreshPaymentOptions_Ajax(tip) {

    var url = 'ajax_cart_payment_options_SI.asp?tip=' + tip;

    if (document.getElementById("collect") != null) {
        if (document.getElementById("collect").checked == true)
            url += "&collect=" + document.getElementById("collect").value;
        else
            url += "&collect=0";
    }

    if (checkIfCADomainJS() == 0)
        url = 'http://' + document.domain + '/' + url;
		
	 url += "&no_cache=" + Math.round((new Date().getTime() * Math.random()));

    ajaxpage(url, 'cartPayOpt');
}

function changeInstall(payment){
	var url = '';
	var nbr_install = 0 ;
	var inx = 0;
	var tip = 0;

	if (payment == 'cash') {
		document.getElementById('pInstallment').style.display = "none";
		document.getElementById('nbr_install').style.display = "none";
		document.getElementById('nbr_install_ccard').style.display = "none";
		document.getElementById('divcartTotal').className = "cartTotal";
		nbr_install = '';	
	}
    
    if (payment == 'install') {
		document.getElementById('pInstallment').style.display = "block";
		document.getElementById('nbr_install').style.display = "block";
		document.getElementById('nbr_install_ccard').style.display = "none";
		document.getElementById('divcartTotal').className  = "cartTotal instTotal";

		if (document.getElementById('nbr_install') != null) {
            inx = document.getElementById('nbr_install').selectedIndex;
            nbr_install = document.getElementById('nbr_install').options[inx].text;
            tip = 11;
        }
    }

    if (payment == 'ccard') {
		document.getElementById('pInstallment').style.display = "block";
		document.getElementById('nbr_install').style.display = "none";
		document.getElementById('nbr_install_ccard').style.display = "block";
		document.getElementById('divcartTotal').className  = "cartTotal instTotal";

		if (document.getElementById('nbr_install_ccard') != null) {
            inx = document.getElementById('nbr_install_ccard').selectedIndex;
            nbr_install = document.getElementById('nbr_install_ccard').options[inx].text;
        }
	}

    document.getElementById('sInstallment').innerHTML = nbr_install;
	document.getElementById('installmentText').value = nbr_install;

	RefreshPrices_Ajax(tip);
}

function isNumeric(inputValue) {
    return typeof inputValue === 'number' && isFinite(inputValue);
}

function DownloadPDF(link) {
    window.open(link);
    return false;
}

function disableEnterKey(e) {
    var key;

    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13)
        return false;
    else
        return true;
}

function fbs_click(u) {
	if (u == '')
	u = location.href;

	t = document.title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function BMICalculator_validator(form_id) {
    var weight = $("#bmi_weight").val().replace(",", ".");
    //var height = document.form_bmi_calculator.bmi_height.value.replace(",", ".");
	var height = $("#bmi_height").val().replace(",", ".");
    var error_B = false;

    if (!floatValidator(weight)) {
        $('#bmi_weight').addClass("error");
        error_B = true;
    }

    if (!floatValidator(height)) {
        $('#bmi_height').addClass("error");
        error_B = true;
    }

    if (error_B) {
        $('#bmi_error').show();
    }
    else {
        if (weight <= 10) {
            $('#bmi_error').show();
            error_B = true;
        }
        else if (height < 33) {
            $('#bmi_error').show();
            error_B = true;
        }
    }

    if (!error_B) {
        var h = height / 100;
        var bmi = String(Math.round((weight / (h * h)) * 100) / 100);
        $('#bmi_value').val(bmi);
		$('#form_bmi_calculator').attr('action', $('#form_bmi_calculator').attr('action') + '&bmi_value=' + bmi);
        document.form_bmi_calculator.submit();
    }
}

function SIWCalculator_validator(form_id) {
    var weight = $("#SIW_Weight").val().replace(",", ".");
    //var height = document.form_bmi_calculator.bmi_height.value.replace(",", ".");
    var height = $("#SIW_Height").val().replace(",", ".");
    var error_S = false;

    if (!floatValidator(weight)) {
        $('#SIW_Weight').addClass("error");
        error_S = true;
    }

    if (!floatValidator(height)) {
        $('#SIW_Height').addClass("error");
        error_S = true;
    }

    if (error_S) {
        $('#siw_error').show();
    }
    else {
        if (weight <= 10) {
            $('#siw_error').show();
            error_S = true;
        }
        else if (height < 33) {
            $('#siw_error').show();
            error_S = true;
        }
    }

    if (!error_S) {
        for (var i = 0; i < document.simple_form_weight_calculator.SIW_radio_G.length; i++) {
            if (document.simple_form_weight_calculator.SIW_radio_G[i].checked) {
                var rad_val = document.simple_form_weight_calculator.SIW_radio_G[i].value;
            }
        }
        if (rad_val = "men") {
            var siw = String(Math.round((height - 100) - ((height - 100) * 0.1)));
        }
        else if (rad_val = "woman") {
            var siw = String(Math.round((height - 100) + ((height - 100) * 0.15)));
        }
                
        
        $('#siw_value').val(siw);
        $('#simple_form_weight_calculator').attr('action', $('#simple_form_weight_calculator').attr('action') + '&siw_value=' + siw);
        document.simple_form_weight_calculator.submit();
    }
}

function CCNCalculator_validator(form_id) {
    var weight = $("#ccn_weight").val().replace(",", ".");
    //var height = document.form_bmi_calculator.bmi_height.value.replace(",", ".");
    var height = $("#ccn_height").val().replace(",", ".");
    var age = $("#ccn_age").val().replace(",", ".");
    var error_C = false;

    if (!floatValidator(weight)) {
        $('#ccn_weight').addClass("error");
        error_C = true;
        alert("teža");
    }

    if (!floatValidator(height)) {
        $('#ccn_height').addClass("error");
        error_C = true;
        alert("visok");
    }

    if (!floatValidator(age)) {
        $('#ccn_age').addClass("error");
        error_C = true;
        alert("star");
    }
    
    if (error_C) {
        $('#ccn_error').show();
    }


    else {
        if (weight <= 10) {
            $('#ccn_error').show();
            error_C = true;
            alert("teža manjša od 10");
        }
        else if (height < 33) {
            $('#ccn_error').show();
            error_C = true;
            alert("velikost manjša od 33");
        }
        else if (age < 18) {
            $('#ccn_error').show();
            error_C = true;
            alert("starost < 18");
        }
    }

    if (!error_C) {
        
        var Select_Value = "";
        for (var i = 0; i < document.form_ccn_calculator.CCN_radio_G.length; i++) {
            if (document.form_ccn_calculator.CCN_radio_G[i].checked) {
                rad_val = document.form_ccn_calculator.CCN_radio_G[i].value;
            }
        }
        
        Select_Value = $("#ccn_selectAct").val();

        if (rad_val == "men") {
            var gend = (66.5 + (13.75 * weight) + (5 * height) - (6.77 * age));
        }
        else if (rad_val == "woman") {
            var gend = (655.1 + (9.56 * weight) + (1.85 * height) - (4.67 * age));
        }

        switch (Select_Value) {
            case "0":
                var ccn_tmp = (gend * 1.2);
                break;
            case "1":
                var ccn_tmp = (gend * 1.375);
                break;
            case "2":
                var ccn_tmp = (gend * 1.55);
                break;
            case "3":
                var ccn_tmp = (gend * 1.725);
                break;
        }
        
        var ccn = ccn_tmp.toFixed(2);
        $('#ccn_value').val(ccn);
        $('#form_ccn_calculator').attr('action', $('#form_ccn_calculator').attr('action') + '&siw_value=' + ccn);
        document.form_ccn_calculator.submit();
     }
}



function BMICalculator_validator_v2(default_action) {
    var weight = $("#bmi_weight").val().replace(",", ".");
    //var height = document.form_bmi_calculator.bmi_height.value.replace(",", ".");
	var height = $("#bmi_height").val().replace(",", ".");
    var error_B = false;

    if (!floatValidator(weight)) {
        $('#bmi_weight').addClass("error");
        error_B = true;
    }

    if (!floatValidator(height)) {
        $('#bmi_height').addClass("error");
        error_B = true;
    }

    if (error_B) {
        $('#bmi_error').show();
    }
    else {
        if (weight <= 10) {
            $('#bmi_error').show();
            error_B = true;
        }
        else if (height < 33) {
            $('#bmi_error').show();
            error_B = true;
        }
    }

    if (!error_B) {
        var h = height / 100;
        var bmi = String(Math.round((weight / (h * h)) * 100) / 100);
        $('#bmi_value').val(bmi);
		$('#form_bmi_calculator').attr('action', default_action + '&bmi_value=' + bmi);
        document.form_bmi_calculator.submit();
    }
}

function floatValidator(str) {
    return /^[-+]?[0-9]+(\.[0-9]+)?$/.test(str);
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function deliveryFreeFormSubmit() {
    var isError = false;

    if (isValidEmail(document.getElementById("email_dostava_free"))) {
        isError = true;
    }

    if (document.getElementById("checkRules").checked == true) {
        document.getElementById("checkboxRules").setAttribute("class", "");
    }
    else {
        document.getElementById("checkboxRules").setAttribute("class", "error");
        isError = true
    }

    if (!isError) {
        document.forms['form_dostava_free'].submit();
    }
}

function checkIfCADomainJS() {
    var dom

    dom = document.domain;

    if (dom == 'ca.avenija.com' || dom == 'ca.testavenija.com') {
        return 1;
    }
    else {
        return 0;
    }
}


function redirectToParent(linkid) {
    if (trim(document.getElementById('clubCard').value) != '') {
        opener.location.href = 'activateClubCard.asp?redirectParam=' + document.getElementById('redirectParam').value + '&clubCard=' + document.getElementById('clubCard').value;
        window.close();
    }
    else {
        document.getElementById('clubCard').className = 'error';
    }
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");

}
