var W3CDOM = (document.getElementsByTagName && document.createElement);

if (W3CDOM)
{
    var errorNode;
    errorNode = document.createElement('div');
    errorNode.className = "errormsg";
}

function clearErrors(forma)
{
	if (!W3CDOM) return;
    // czyszczenie bledow poszczegolnych pol
    var pola = forma.getElementsByTagName("input");
    for (i = 0; i< pola.length; i++) {
        if (blad_pola = document.getElementById(pola[i].name.replace(/[\[\]]/g,'\.')+"_error"))
            blad_pola.innerHTML = '';
    }
    // i kontenera
        document.getElementById('form_errors').innerHTML='';
}

/* dodalem to, bo nie chce namieszac - chodzi o sprawdzanie tez select*/
function clearAllErrors(forma)
{
	if (!W3CDOM) return;
    // czyszczenie bledow poszczegolnych pol
    var pola = forma.getElementsByTagName("input");
    for (i = 0; i< pola.length; i++) {
        if (blad_pola = document.getElementById(pola[i].name.replace(/[\[\]]/g,'\.')+"_error"))
            blad_pola.innerHTML = '';
    }

    var pola = forma.getElementsByTagName("select");
    for (i = 0; i< pola.length; i++) {
        if (blad_pola = document.getElementById(pola[i].name.replace(/[\[\]]/g,'\.')+"_error"))
            blad_pola.innerHTML = '';
    }

    // i kontenera
        document.getElementById('form_errors').innerHTML='';
}



function verifySimpleSearch(form) {
    if (Trim(form.elements['search'].value).length < 3) {
        alert('Could not search - search term must be at least 3 chars long...');
        return false;
    }
    return true;
}

function verifyAddToCart(form) {
    var wynik=true;
    clearErrors(form);
    form.elements['amount'].value = parseInt(form.elements['amount'].value);
    if (isNaN(form.elements['amount'].value))
        form.elements['amount'].value = "0";
    if (parseInt(form.elements['amount'].value) <= 0 )
        wynik = addError('Amount to purchase must be greater than zero.');
    for (var i = 0 ; i < form.elements.length; i++) {
        if (form.elements[i].name.match(/oc_\d+/)) { // this is an option field
            if (form.elements[i].name.match(/^oc_\d+$/) // options for base product
               || form.elements[i].name.match(/^element_options\[\d+\]\[oc_\d+\]$/) ) { // options for package elements
                if (getSingleInputValue(form.elements[i]) == -1)
                    wynik = addError('Not all options for this product are chosen.');
            } else { // options for additional product
                match = form.elements[i].name.match(/^additional_options\[(\d+)\]\[oc_\d+\]$/);
                if (form.elements['additional[' + match[1] + ']'].checked &&
                    getSingleInputValue(form.elements[i]) == -1)
                        wynik = addError('Not all options for this product are chosen.');
            }

        }
    }
    if (!wynik)
        alert("Could not add to cart - please correct errors...");
    return wynik;
}

function handleBuyXGetY(input, src_amount, dest_amount, dest_product_id) {
    var entered_amount = input.form.elements['amount'].value;
    var div = document.getElementById('options' + dest_product_id);

    switch (input.checked) {
        case true: // enable promotion
            // disable all other promotions
            for (var i = 0 ; i < input.form.elements.length; i++) {
                if (input.form.elements[i].name.match(/^additional\[\d+\]/)
                    && input.form.elements[i].type == 'checkbox' && input.form.elements[i] != input) {
                    input.form.elements[i].checked = false;

                    input.form.elements[i].onclick();
                }
            }
            // correct the amount of source product
            if (parseInt(entered_amount) < src_amount) {
                input.form.elements['amount'].value = src_amount;
                var text = "Amount has been increased to " + src_amount + " to comply with promotion rules.";
                text += "\nIf you want different options for each product, correct the amount and add separate product(s) separately and the promotion will still get applied in the basket.";
                alert(text);
            }

            // add calculated amount of destination product
            var howMany = Math.floor(input.form.elements['amount'].value / src_amount);
            input.form.elements['additional[' + dest_product_id + ']'].value = dest_amount * howMany;
            if (div)
                div.style.display = 'block';
        break;
        case false: // disable promotion
            input.form.elements['additional[' + dest_product_id + ']'].value = "";
            if (div)
                div.style.display = 'none';
        break;
    }
}

function ReadISO8601date(Q) {
    var T;
    if ((T = /^(\d+)([-\/])(\d\d)(\2)(\d\d)$/.exec(Q)) == null) {
        return -2;
    }
    for (var j = 1; j <= 5; j += 2) {
        T[j] = +T[j];
    }
    if (!ValidDate(T[1], T[3] - 1, T[5])) {
        return -1;
    }
    return [T[1], T[3], T[5]];
}


function ValidDate(y, m, d) {
    with (new Date(y, m, d)) {
        return (getMonth() == m && getDate() == d);
    }
}

function DiffDays(S1, S2) {
    var X = ReadISO8601date(S1);
    if (X < 0) {
        return "Date 1 bad";
    }
    var Y = ReadISO8601date(S2);
    if (Y < 0) {
        return "Date 2 bad";
    }
    var Dx = Date.UTC(X[0], X[1] - 1, X[2]);
    var Dy = Date.UTC(Y[0], Y[1] - 1, Y[2]);
    return (Dx - Dy) / 86400000;
}

function leadingZero(nr)
{
	if (nr < 10) nr = "0" + nr;
	return nr;
}
function takeYear(theDate)
{
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}

// recalculate price (assuming price included in js)
function recalculatePrice(actual, next, form) {
    price = actual;
    from = form.elements['hir_from'].value; from_day = from.substring(0,2); from_mon = from.substring(3,5); from_y = from.substring(6,10);
    new_from = from_y+'-'+from_mon+'-'+from_day;

    to = form.elements['hir_to'].value; to_day = to.substring(0,2); to_mon = to.substring(3,5); to_y = to.substring(6,10);
    new_to = to_y+'-'+to_mon+'-'+to_day;

    fr2to = DiffDays(new_to, new_from);
    upgrade_fee = 0;

    var pola = form.getElementsByTagName("input");
    for (i = 0; i< pola.length; i++) {
      name = pola[i].name;
      checked = pola[i].checked;
      pre = name.substring(0, 2);
      len = name.length;
      id = name.substring(2, len);
      if ((pre=='u_') && (checked)) {
        upgrade_fee = upgrade_fee+parseFloat(form.elements['p_'+id].value);
      }

    }
    price = price + upgrade_fee;
    if (fr2to>3) price = price + (fr2to-3)*next;

    num = Math.floor(price*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    price = num+'.'+cents;
    return confirm('Note that price of hiring this kilt will take �'+price+' refering to chosen options. Do you confirm hiring?');
}

// validate hiring product
function verifyAddHiringProductToCart(form) {
    var wynik=true;
    var not_all = false;
    var not_ent = false;
    clearErrors(form);
    var pola = form.getElementsByTagName("select");
    for (i = 0; i< pola.length; i++) {
        if (pola[i].value && pola[i].value == -1) { not_all = true; wynik = addAttention(pola[i].name) }
    }
    var pola = form.getElementsByTagName("input");
    for (i = 0; i< pola.length; i++) {
        if (pola[i].value.length==0) { not_ent = true; wynik = addAttention(pola[i].name) }
    }

    if (not_all) wynik = addError('Not all options for this product are chosen.');
    if (not_ent) { wynik = addError('Please fill in missing fields.'); }

    from = form.elements['hir_from'].value; from_day = from.substring(0,2); from_mon = from.substring(3,5); from_y = from.substring(6,10);
    new_from = from_y+'-'+from_mon+'-'+from_day;

    func = form.elements['hir_func'].value; func_day = func.substring(0,2); func_mon = func.substring(3,5); func_y = func.substring(6,10);
    new_func = func_y+'-'+func_mon+'-'+func_day;

    to = form.elements['hir_to'].value; to_day = to.substring(0,2); to_mon = to.substring(3,5); to_y = to.substring(6,10);
    new_to = to_y+'-'+to_mon+'-'+to_day;

    today = new Date();
    Year = takeYear(today);
    Month = leadingZero(today.getMonth()+1);
    Day = leadingZero(today.getDate());
    new_today = Year+'-'+Month+'-'+Day;

    if (wynik) {
      fr2fu = DiffDays(new_func, new_from);
      fu2to = DiffDays(new_to, new_func);
      fr2to = DiffDays(new_to, new_from);
      tod2fr= DiffDays(new_from, new_today);


      if (tod2fr<3) { wynik = addError('Starting date should be at least 3 days from today!','hir_from'); }
      if (fr2fu<0) { wynik = addError('Function date can\'t be sooner than starting date!','hir_func'); }
      if (fu2to<0) { wynik = addError('Function date can\'t be later that returning date!','hir_func'); }
      if (fr2to<3) { wynik = addError('Kilt can be hire minimal for 3 days!', 'hir_to'); }
    }

    if (!wynik)
        alert("Could not add to cart - please correct errors...");
    return wynik;
}

// adds only '!'
function addAttention(field) {
    title = field;
  	if (!W3CDOM) return false;
	  if (field) {// zawiadomienie o bledzie przy polu formularza
      field_error = document.getElementById(field+"_error");
    }
    if (field_error)
        field_error.innerHTML='<span title="'+title+'">(!)&nbsp;</span>';
    return false;
}

function verifyQuestion(form) {
    var wynik=true;
    clearErrors(form);
    if (!isEmail(form.elements['email'].value))
        wynik = addError('You need to enter correct e-mail address.', 'email');
    if (Trim(form.elements['question'].value).length < 15)
        wynik = addError('Question must be between 15 and 200 chars long.', 'question');
    if (!wynik)
        alert("Could not complete request - please correct errors...");
    return wynik;
}

function verifyContactForm(form) {
    var wynik=true;
    clearErrors(form);
    if (!isEmail(form.elements['email'].value))
        wynik = addError('You need to enter correct e-mail address.', 'email');
    if (Trim(form.elements['question'].value).length < 15)
        wynik = addError('Your message is to short.', 'message');
    if (Trim(form.elements['question'].value).length > 1500)
        wynik = addError('Your message is too long.', 'message');

    if (!wynik)
        alert("Could not complete request - please correct errors...");
    return wynik;
}

function verifyCreditForm(form) {
    var wynik=true;
    clearAllErrors(form);
    if (isBlank(form.elements['code'].value))
        wynik = addError('You need to enter security code.', 'code');

    if (isBlank(form.elements['number'].value))
        wynik = addError('You need to enter credit card number.', 'number');

    if (form.elements['endDateM'].value=='-1')
        wynik = addError('You need to enter credit card expire date month.', 'endDateM');

    if (form.elements['endDateY'].value=='-1')
        wynik = addError('You need to enter credit card expire date year.', 'endDateY');

    if (!wynik)
        alert("Could not complete request - please correct errors...");
    return wynik;
}


function verifyEmailToFriend(form) {
    var wynik=true;
    clearErrors(form);
    if (!isEmail(form.elements['email'].value))
        wynik = addError('You need to enter correct e-mail address.', 'email');

    if (!isEmail(form.elements['email_friend'].value))
        wynik = addError('You need to enter correct e-mail address.', 'email_friend');

    if (Trim(form.elements['message'].value).length < 15)
        wynik = addError('Message must be between 15 and 200 chars long.', 'message');

    if (!wynik)
        alert("Could not complete request - please correct errors...");
    return wynik;
}

function verifySearch(form) {
    var wynik=true;
    clearErrors(form);
    var option_chosen=false;
    for (var i = 0 ; i < form.elements.length; i++) {
        if (form.elements[i].name.match(/^oc\[\d+\]$/)
            && form.elements[i].value != -1)
            option_chosen = true;
    }

    if (option_chosen) {
        if (!isBlank(form.elements['name'].value) && Trim(form.elements['name'].value).length < 3)
            wynik = addError("'Product name' criteria must be at least 3 characters long", 'name');
        if (!isBlank(form.elements['category'].value) && Trim(form.elements['category'].value).length < 3)
            wynik = addError("'Product category' criteria must be at least 3 characters long", "category");
    } else {
        if (isBlank(form.elements['name'].value)
            && isBlank(form.elements['category'].value)
            && isBlank(form.elements['id'].value)
        )
            wynik = addError("Enter product name, ID, or its category, or choose product options from the list", "name");
        if (!isBlank(form.elements['name'].value) && Trim(form.elements['name'].value).length < 3)
            wynik = addError("'Product name' criteria must be at least 3 characters long", 'name');

        if (!isBlank(form.elements['id'].value) && ! new RegExp('^\\d+$').test(form.elements['id'].value))
            wynik = addError("'Product ID' must be a number", 'id');

        if (!isBlank(form.elements['category'].value) && Trim(form.elements['category'].value).length < 3)
            wynik = addError("'Product category' criteria must be at least 3 characters long", "category");
    }
    if (!wynik)
        alert("Could not search - please correct errors...");
    return wynik;
}

function updateAddressRadios(form, radio_group_name) {
    if (form.elements[radio_group_name] && form.elements[radio_group_name].length) {// sa opcje do wyboru, czyli jest opcja dodania pola
        form.elements[radio_group_name][form.elements[radio_group_name].length-1].checked = true; //select last radio (i.e., add new)
    }
}

function verifyAddresses(form, array_name, radio_group_name) {
    var wynik=true;
    clearErrors(form);
    if (typeof radio_group_name != "undefined") {

        if (form.elements[radio_group_name+'[address_id]'] && form.elements[radio_group_name+'[address_id]'].length) {// sa opcje do wyboru, czyli jest opcja dodania pola
            // ale wybrano inna
            if (getRadioValue(form.elements[radio_group_name+'[address_id]']) != "-1")
                return true;
        }
    }

    if (Trim(form.elements[array_name+'[address_title]'].value).length < 3)
        wynik = addError('Name and surname must be at least 3 chars long', array_name+'[address_title]');

    if (Trim(form.elements[array_name+'[address_line1]'].value).length < 5)
        wynik = addError('Address first line must be at least 5 chars long', array_name+'[address_line1]');

    form.elements[array_name+'[address_line2]'].value = Trim(form.elements[array_name+'[address_line2]'].value);

    if (Trim(form.elements[array_name+'[address_city]'].value).length < 4)
        wynik = addError('Address city must be at least 5 chars long', array_name+'[address_city]');

    if (Trim(form.elements[array_name+'[address_zipcode]'].value).length == 0)
        wynik = addError('Postal code must not be empty', array_name+'[address_zipcode]');

    if (Trim(form.elements[array_name+'[country_id]'].options[form.elements[array_name+'[country_id]'].selectedIndex].value).length == 0)
        wynik = addError('Please choose country from the list...', array_name+'[country_id]');

   if (array_name == 'billing_form') {// additional test for billing address
        if (!isBlank(form.elements[array_name+'[address_phone]'].value) && !isPhone(form.elements[array_name+'[address_phone]'].value))
            wynik = addError('You need to enter correct phone number. You may use digits, (), - and leading + to format phone number.', array_name+'[address_phone]');

        if (form.elements['customer_email'] && !isBlank(form.elements['customer_email'].value)
            && !isEmail(form.elements['customer_email'].value))
            wynik = addError('You need to enter correct e-mail address. Empty this field if you don\'t have an e-mail address', 'customer_email');

        if (form.elements['customer_email'] && isBlank(form.elements['customer_email'].value)
            && isBlank(form.elements[array_name+'[address_phone]'].value))
            wynik = addError('Please provide us with phone number or e-mail address to complete your order.',array_name+'[address_phone]');

    }
    if (!wynik)
        alert("Request could not be sent - please correct errors...");
    return wynik;
}

function setAction(button, field, value) {
    if (typeof field != 'undefined')
        button.form.elements[field].value = value;
    button.form.elements['actn'].value = button.name;
    button.form.submit();
    return false;
}

function setFormAction(form_name, button, field, value) {
    form = document.forms[form_name];
    if (typeof field != 'undefined')
        form.elements[field].value = value;
    form.elements['actn'].value = button.name;
    form.submit();
    return false;
}


function addError(title, field)
{
    if (!W3CDOM)
        return false;
    var errorBlock = document.getElementById('form_errors');

	if (!title) title = "UNNAMED ERROR!";

	if (typeof errorBlock != 'undefined') {
	   var newError = errorNode.cloneNode(true); // dodawanie komunikatu o bledzie
	   newError.appendChild(document.createTextNode("Error: "+title));
	   errorBlock.appendChild(newError);
	}

	if (field) {// zawiadomienie o bledzie przy polu formularza
	    field = field.replace(/[\[\]]/g,'\.');   //zamiana [ i ] na kropki
        field_error = document.getElementById(field+"_error");
    }
    if (typeof field_error != 'undefined' && field_error != null)
        field_error.innerHTML='<span title="'+title+'">(!)&nbsp;</span>';

	return false;
}

function getRadioValue (radioButtonOrGroup) {
  var value = null;
  if (radioButtonOrGroup.length) { // group
    for (var b = 0; b < radioButtonOrGroup.length; b++)
      if (radioButtonOrGroup[b].checked)
        value = radioButtonOrGroup[b].value;
  }
  else if (radioButtonOrGroup.checked)
    value = radioButtonOrGroup.value;
  return value;
}

function isEmail(str) {
// przepuszcza adres mailowy
        if(!str.match(/^[\w]{1}[\w\.\-_]*@[\w]{1}[\w\-_\.]*\.[\w]{2,6}$/i)) {  //sam adres
		if (str.match(/<[\w]{1}[\w\.\-_]*@[\w]{1}[\w\-_\.]*\.[\w]{2,6}>$/i))  //nazwa i adres
			return true;
		else
	 		return false;
        } else {
            return true;
        }
}

function isPhone(s)
{

     // Check for correct phone number
     rePhoneNumber = new RegExp(/^\+?[0-9()\- ]{6,}$/);

     return rePhoneNumber.test(s);
}

function stock(opts, product_id, link) {
    var add_query = "";
    for (i=0; i<opts.length; i++) {
        elem = document.getElementById("oc_"+opts[i]);
        if (elem.options) {
            sel = elem.options[elem.selectedIndex].value;
        } else {
            sel = elem.value;
        }
        add_query += "&oc_"+opts[i]+"="+sel;
    }

    var obj_stockwindow = window.open(link+"?product_id="+product_id+add_query, 'ChooseOption', 'width=550,height=470,status=no,resizable=yes,top=200,left=200,dependent=yes,alwaysRaised=yes,scrollbars=yes');
}

function assignOption(id, link, options, type) {
    if (typeof options=='undefined') options = 'width=530,height=270,status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes';
    elem = document.getElementById(id);
    sel = elem.options[elem.selectedIndex].value;
    var obj_clanwindow = window.open(link+"&selected="+sel+"&type="+type, 'ChooseOption', options);
    obj_clanwindow.opener = window;
	obj_clanwindow.focus();
}
function checkWeight(link, product_id, oc, oc53, options) {
    if (typeof options=='undefined') options = 'width=330,height=50,status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes';
    option_sel = document.getElementById(oc);
    option_id = option_sel.options[option_sel.selectedIndex].value;
    var obj_weightwindow = window.open(link+"?option_id="+option_id+"&oc53="+oc53+"&product_id="+product_id, 'ChooseOption', options);
    obj_weightwindow.opener = window;
	obj_weightwindow.focus();
}

function roundPrice(price) {
    num = Math.floor(price*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    price = num+'.'+cents;
    return price;
}
function checkPrice(form, price, currency_rate, currency_code, to_confirm) {
    calButton = document.getElementById('recalculatePrice');
    if (!calButton) return true;

    price_mod = 0;
    for (var i = 0 ; i < form.elements.length; i++) {
        text = form.elements[i].name;
        if (text.match(/pr_\d+/)) {
            temp_value = text.substr(3);
            pos = temp_value.indexOf("_");
            option_category_id = temp_value.substr(0,pos);
            option_id = temp_value.substr(pos+1);
            oc = form.elements['oc_'+option_category_id];
            current_value = oc.options[oc.selectedIndex].value;
            if (current_value==option_id) {
                price_mod += (parseFloat(form.elements[i].value,10) || 0);
            }
        }
    }

    price_net = price+price_mod;
    price_gross = (price_net*(17.5/100))+price_net;

    if (currency_code.length>0) {
        price_net = price_net*parseFloat(currency_rate,10);
        price_gross = price_gross*parseFloat(currency_rate,10);
    }

    amount = parseInt(document.forms['product_form'].elements['amount'].value);
    if (isNaN(amount)) return false;

    price_gross = roundPrice(price_gross*amount);
    price_net = roundPrice(price_net*amount);

    if (currency_code.length>0) {
        price_gross = currency_code+" "+price_gross;
        price_net = currency_code+" "+price_net;
    }

    if (to_confirm)
        return confirm("Total price: "+price_gross+" gross"+", "+price_net+" net. \n (calculated without promotions) \n Do you want to add it do basket?");
        else
        alert("Total price: "+price_gross+" gross"+", "+price_net+" net. \n (calculated without promotions)");
    return false;
}

function addOptions(option_txt, option_val, price_mod, oc53) {
    weight_opt = document.getElementById(oc53);
    weight_opt.options.length = 0;
    weight_opt.options[weight_opt.options.length] = new Option(option_txt, option_val);

    if (option_val!='-1') {
        price_mod = parseFloat(price_mod);
        price = document.getElementById(oc53+'_weight_price_modifier');
        price.name = 'pr_53_'+option_val;
        price.value = price_mod;
    }
}

if (typeof liveSearchInit == "function")
    window.onload = function() {liveSearchInit()};

// the functions in this file require the supplementary library lib.js

// These defaults should be changed the way it best fits your site
var _POPUP_FEATURES = '';

function raw_popup(url, target, features) {
    // pops up a window containing url optionally named target, optionally having features
    if (isUndefined(features)) features = _POPUP_FEATURES;
    if (isUndefined(target  )) target   = '_blank';
    var theWindow = window.open(url, target, features);
    theWindow.focus();
    return theWindow;
}

function link_popup(src, features) {
    // to be used in an html event handler as in: <a href="..." onclick="link_popup(this,...)" ...
    // pops up a window grabbing the url from the event source's href
    return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', features);
}

function event_popup(e) {
    // to be passed as an event listener
    // pops up a window grabbing the url from the event source's href
    link_popup(e.currentTarget);
    e.preventDefault();
}

function event_popup_features(features) {
    // generates an event listener similar to event_popup, but allowing window features
    return function(e) { link_popup(e.currentTarget, features); e.preventDefault() }
}

function isUndefined(v) {
    var undef;
    return v===undef;
}
function insertInternalTracker(session_name, session_id) {
  var container = document.getElementById("internal_tracker_container");
  var _string = "<img width='1' height='1' src='stats.php?"+session_name+"="+session_id+"&amp;url="+encode64(document.location.href)+"' alt='' />";
  container.innerHTML = _string;
}

<!-- FROM PAGE http://rumkin.com/tools/compression/base64.php
function encode64(input) {
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);

   return output;
}
