
function ajaxRequest(url, data, processor)
{	
    $.post(url, data, processor, "json");
}

function evalJson(json)
{
    return eval('(' + json + ')');
}
            
////////////////////////////////////////////////////////////////////////////////

// URL creating
function createUrl(value)
{
    var newVal = convertToASCI(value);
    return newVal.toLowerCase().replace(/[^a-zA-Z0-9]+/g, "-");
}

// Conver bad chars to asci
function convertToASCI(str)
{
    str = str.toLowerCase();
    var replace   = new Array('æ', 'ø', 'å', 'ē', 'ū', 'ī', 'ā', 'š', 'ģ', 'ķ', 'ļ', 'ž', 'č', 'ņ', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ь', 'ю', 'я', 'ъ', 'ы');
    var by        = new Array('ae', 'oe', 'aa', 'e', 'u', 'i', 'a', 's', 'g', 'k', 'l', 'z', 'c', 'n', 'a', 'b', 'v', 'g', 'd', 'e', 'e', 'zh', 'z', 'i', '', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'sh', 'j', 'ju', 'ja', '', 'y');
    for (var c = 0; c < 50; c++) {
        for (var i = 0; i < replace.length; i++) {
            str = str.replace(replace[i], by[i]);
        }
    }
    return str;
}

// Check url value
function checkUrl(id)
{
    $("#" + id).val($("#" + id).val().toLowerCase().replace(/[^a-zA-Z0-9]+/g, "-"));
}

// JS redirect
function jsRedirect(link)
{
    window.location.href = link;
    return false;
}

// JS history back
function jsBack()
{
    window.history.back();
}

// JS print
function jsPrint()
{
    window.print();
    return false;
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Social networks share functions
 */

// Share Twitter
function shareTwitter(pUrl, pTitle)
{
    if (pUrl === undefined || pUrl == '') {
    	pUrl = document.location.href;
    } else {
    	pUrl = domain+pUrl;
    }
    if (pTitle === undefined || pTitle == '') pTitle = seeShareMessage+document.title;
    window.open('http://twitter.com/share?url=' + encodeURIComponent(pUrl) + '&text=' + encodeURIComponent(pTitle), 'Share','menubar=0,resizable=1,,width=550,height=450');
    return false;
}

// Share Draugiem
function shareDraugiem(pPrefix, pTitle, pUrl)
{
    if (pPrefix === undefined || pPrefix == '') pPrefix = '';
    if (pTitle === undefined || pTitle == '') pTitle = seeShareMessage+document.title;
    if (pUrl === undefined || pUrl == '') {
        pUrl = document.location.href;
    } else { 
        pUrl = domain+pUrl; 
    }
	
    window.open(
        'http://www.draugiem.lv/say/ext/add.php?title=' + encodeURIComponent(pTitle) +
        '&link=' + encodeURIComponent(pUrl) +
        (pPrefix != "" ? '&titlePrefix=' + encodeURIComponent(pPrefix) : ''),
        '',
        'location=1,status=1,scrollbars=0,resizable=0,width=530,height=400'
    );
    return false;
}

// Share Facebook
function shareFB(pUrl)
{
    if (pUrl === undefined || pUrl == '') {
    	pUrl = document.location.href;
    } else {
    	pUrl = domain+pUrl;
    }
    
    function a() {
        if (!window.open('http://www.facebook.com/share.php?u=' + encodeURIComponent(pUrl), 'Share', 'toolbar=0,status=0,resizable=1,width=626,height=436')) {
            document.location.href = 'http://www.facebook.com/share.php?u=' + encodeURIComponent(pUrl);
        }
    }
    if (/Firefox/.test(navigator.userAgent)) {
        setTimeout(a, 0);
    } 
    else {
        a();
    }
    return false;
}

// Share Google+
function shareG(big, pUrl, pTitle)
{
    if (pUrl === undefined || pUrl == '') {
    	pUrl = document.location.href;
    } else {
    	pUrl = domain+pUrl;
    }
    if (pTitle === undefined || pTitle == '') pTitle = document.title;
    window.open('https://m.google.com/app/plus/x/?v=compose&content=' + encodeURIComponent(pTitle) + '' + encodeURIComponent(pUrl), 'gplusshare','width=450,height=300,left='+(screen.availWidth/2-225)+',top='+(screen.availHeight/2-150)+'');
    return false;
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Validation functions
 */

function containsAllowedChars(field)
{
    var value = $(field).val().replace(/\n/g, ''); 
    if (value != '') {
        var regex = /^[a-žA-Ža-zA-Z0-9а-яА-ЯёЁ/\-\–\:\.\,\"\'\’\`\~\?\!\@\#\$\%\^\&\*\(\)\_\+\-\= ]+$/;
        if (!regex.test(value)) return false;
    }
    return true;
}

// Check if field is empty or not
function isFieldEmpty(field, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;

    // Do checking
    if (jQuery.trim($(field).val()) == "") {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if field value is correct e-mail address
function isFieldEmail(field, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;

    // Do checking
    var emailRegex = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]{2,4}$/;
    if (!$(field).val().match(emailRegex)) {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if field value has correct length
function isFieldCorrectLength(field, min, max, set_cursor)
{
    // Set the default values if needed
    if (min === undefined) min = 6;
    if (max === undefined) max = 32;
    if (set_cursor === undefined) set_cursor = false;

    // Do checking
    var len = $(field).val().length;
    if (len < min || len > max) {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if field value is correct security code
function isFieldSecurityCode(field, vallength, set_cursor)
{
    // Set the default values if needed
    if (vallength === undefined) vallength = 5;
    if (set_cursor === undefined) set_cursor = false;

    // Do checking
    if (!/[a-zA-Z0-9]$/.test($(field).val())) {
        if (set_cursor) $(field).focus();
        return true;
    }
    else {
        if ($(field).val().length != vallength) {
            if (set_cursor) $(field).focus();
            return true;
        }
    }
    return false;
}

// Check if field contains numbers only
function isFieldNumbers(field, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;

    // Do checking
    var alphaExp = /^[0-9]+$/;
    if (!$(field).val().match(alphaExp)){
        if (set_cursor) $(field).focus();
        return true;
    }
	
    return false;
}

// Check if field do not contains special characters (allowed only letters and numbers)
function isFieldNoSpecSymbols(field, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;
    
    // Do checking
    var alphaExp = /^[0-9a-zA-Z]+$/;
    if (!$(field).val().match(alphaExp)) {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if field only letters and numbers
function isFieldTextNumbers(field, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;
    
    // Do checking
    if (!/[a-zA-Z0-9]$/.test($(field).val())) {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if field value has correct interval
function isFieldCorrectValueInterval(field, min, max, set_cursor)
{
    // Set the default values if needed
    if (min === undefined) min = 1;
    if (max === undefined) max = 12;
    if (set_cursor === undefined) set_cursor = false;

    // Check length
    var val = $(field).val();
    if (val < min || val > max) {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if checkbox is checked
function isChecked(field, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;
    
    // Do checking
    if ($(field).attr("checked") == false) {
        if (set_cursor) $(field).focus();
        return true;
    }
    return false;
}

// Check if two field values are identical
function isIdentical(field1, field2, set_cursor)
{
    // Set the default values if needed
    if (set_cursor === undefined) set_cursor = false;
    
    // Do checking
    if ($(field1).val() != $(field2).val()) {
        if (set_cursor) $(field2).focus();
        return true;
    }
    return false;
}

// Is correct product number (numbers and letters only)
function checkAlphaNumericsAndPlusSpace(checkString)
{
    var regExp = /^[ A-Za-z0-9+]$/;
    if (checkString != null && checkString != "") {
        for (var i = 0; i < checkString.length; i++) {
            if (!checkString.charAt(i).match(regExp)) {
                return false;
            }
        }
    }
    else {
        return false;
    }
    return true;
}

// Check if value is integer number
function isInteger(s)  {
    var i;
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Captcha code and image refresh function
 */

// Captcha reloader
jQuery.fn.captchaRefresh = function (conf) {
    var config = jQuery.extend({
        src:    '/captcha.png',
        title:  ''
    }, conf);
    return this.each(function (x) {
        var now          = new Date();
        var separator    = config.src.indexOf('?') == -1 ? '?' : '&';
        jQuery('img[src^="' + config.src + '"]', this).attr('title', config.title);
        jQuery('img[src^="' + config.src + '"]', this).attr('src', config.src + separator + now.getTime());
    });
};

////////////////////////////////////////////////////////////////////////////////

/**
 * Converter functions
 */

// Converts value to decimal format with 2 numbers after "."
function toFixedDecimal(val)
{
    val = val.toString().replace(',', '.');
    val = Math.round(val*100)/100;
    return window.Number(val).toFixed(2);
}

// Converts value to integer format
function toFixedInteger(val)
{
    val = val.toString().replace(',', '.');
    val = Math.round(val*100)/100;
    val = Math.round(val*10)/10;
    val = Math.round(val);
    return window.Number(val).toFixed(0);
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Intro functions
 */

function goToCountry(site, url)
{
    if ($("#remember").is(":checked")) {
        $.post(
            domain + intro_url,
            "b2y_country=" + site,
            function() {
                jsRedirect(url);
            }
        );
    }
    else {
        jsRedirect(url);
    }
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Change content
 */
function showInfo(e, id)
{
    $('.categories_ietekme a').each(function(n, element) {
        $(element).removeClass('active');
    });
    $('.content_ietekme').each(function(n, element) {
        $(element).hide();
    });
    $(e).addClass('active');
    $('#info_'+id).show();
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Contacts functions
 */

// Do mail sending after full data validation
function sendMailDo()
{
    var doStatus = true;
    
    if ($('#fullname').val() == $('#fullname').attr('title') || isFieldEmpty('#fullname')) {
        doStatus = false;
        mailShowError('fullname', frmMsg[0]);
    }
    else {
        mailShowOk('fullname');
    }
    
    if (!isFieldEmpty('#phone') && $('#phone').val() != $('#phone').attr('title')) {
        if (isFieldNumbers("input[name=phone]")) {
            doStatus = false;
            mailShowError("phone", frmMsg[1]);
        }
        else {
            mailShowOk("phone");
        }
    }
    
    if ($('#email').val() == $('#email').attr('title') || isFieldEmpty('#email')) {
        doStatus = false;
        mailShowError('email', frmMsg[2]);
    }
    else {
        if (isFieldCorrectLength("#email", 5, 50)) {
            doStatus = false;
            mailShowError('email', frmMsg[3]);
        }
        else {
            if (isFieldEmail("#email")) {
                doStatus = false;
                mailShowError('email', frmMsg[4]);
            }
            else {
                mailShowOk('email');
            }
        }
    }
    
    if ($('#question').val() == $('#question').attr('title') || isFieldEmpty('#question')) {
        doStatus = false;
        mailShowError('question', frmMsg[5]);
    }
    else {
        mailShowOk('question');
    }
    
    if (doStatus) {
        $.post(
            domain + "ajax.php",
            "aa=contacts_mail&ac=" + bCountry + "&al=" + bLang + "&question=" + $('#question').val() + "&fullname=" + $('#fullname').val() + "&phone=" + $('#phone').val() + "&email=" + $('#email').val(),
            function(data) {
                var returndata = JSON.parse(data);
                if (returndata != null && returndata != undefined) {
                    if (parseInt(returndata.status) == 0) {
                        // ok
                        $('#fullname').val($('#fullname').attr('title'));
                        $('#phone').val($('#phone').attr('title'));
                        $('#email').val($('#email').attr('title'));
                        $('#question').val($('#question').attr('title'));
                        mailHideIcons('fullname');
                        mailHideIcons('phone');
                        mailHideIcons('email');
                        mailHideIcons('question');
                        $('#okMsg').html(returndata.message);
                        $('#okMsg').attr('style', 'display: block;');
                    }
                    else {
                        // error
                        if (returndata.message_name != '') mailShowError('fullname', returndata.message_name);
                        else mailShowOk('fullname');
                        if (returndata.message_phone != '') mailShowError('phone', returndata.message_phone);
                        else mailShowOk('phone');
                        if (returndata.message_email != '') mailShowError('email', returndata.message_email);
                        else mailShowOk('email');
                        if (returndata.message_question != '') mailShowError('question', returndata.message_question);
                        else mailShowOk('question');
                        $('#okMsg').html('');
                        $('#okMsg').attr('style', 'display: none;');
                    }
                }
            }
        );
    }
    else {
        $('#okMsg').html('');
        $('#okMsg').attr('style', 'display: none;');
    }
    
    return false;
    
}

// Contacts show error icon and message
function mailShowError(field, msg)
{
    if (field == 'email') $('#' + field).parent().removeClass('long_ok').addClass('long_error');
    else if (field == 'question') $('#' + field).parent().removeClass('textarea_ok').addClass('textarea_error');
    else $('#' + field).parent().removeClass('ok').addClass('error');
    $('#' + field + 'Err').html(msg);
    $('#' + field + 'Err').attr('style', 'display: block;');
}

// Contacts show ok icon
function mailShowOk(field)
{
    if (field == 'email') $('#' + field).parent().removeClass('long_error').addClass('long_ok');
    else if (field == 'question') $('#' + field).parent().removeClass('textarea_error').addClass('textarea_ok');
    else $('#' + field).parent().removeClass('error').addClass('ok');
    $('#' + field + 'Err').html('');
    $('#' + field + 'Err').attr('style', 'display: none;');
}

// Hide ok/error icons
function mailHideIcons(field)
{
    if (field == 'email') $('#' + field).parent().removeClass('long_error').removeClass('long_ok');
    else if (field == 'question') $('#' + field).parent().removeClass('textarea_error').removeClass('textarea_ok');
    else $('#' + field).parent().removeClass('error').removeClass('ok');
    $('#' + field + 'Err').html('');
    $('#' + field + 'Err').attr('style', 'display: none;');
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Shops functions
 */

var geocoder;
var map;
function initializeMap(lat, lng, zoom)
{
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat,lng);
    var myOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: true,
        panControl: false,
        scaleControl: false
    }
    map = new google.maps.Map(document.getElementById("map_shops"), myOptions);
}
function codeMapAddress(address, title, text)
{
    geocoder.geocode(
        {'address': address}, 
        function(results, status){
            if (status == google.maps.GeocoderStatus.OK) {
                //map.setCenter(results[0].geometry.location);
                //map.fitBounds(results[0].geometry.viewport);
                var marker = new google.maps.Marker({
                    map: map, 
                    position: results[0].geometry.location,
                    icon: '/images/design/map_icon.png',
                    title: title
                });
                var infowindow = new google.maps.InfoWindow({
                    content: text
                });
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, marker);
                });
            }
        }
    );
}

// Submit filter search form
function filterShops()
{
    $('#search').val('ok');
    $('#shopsForm').submit();
}

// Hide/Show shop item panel with addresses
function shopAddressPanel(shopid)
{
    if ($('#shopTitle' + shopid).hasClass('active') == true) {
        $('#shopTitle' + shopid).removeClass('active');
        $('#shopAdr' + shopid).slideUp();
    }
    else {
        $('#shopTitle' + shopid).addClass('active');
        $('#shopAdr' + shopid).slideDown();
    }
}

// Load cities list
function loadCities(country_id)
{
    $.post(
        domain + "ajax.php",
        "aa=cities_list&ac=" + bCountry + "&al=" + bLang + "&value=" + country_id,
        function(data) {
            var returndata = JSON.parse(data);
            if (returndata != null && returndata != undefined) {
                if (parseInt(returndata.status) == 0) {
                    $('#shop_city').val(returndata.message);
                    $('.select-city4 dl.select dt a span').html(returndata.message);
                    $('.select-city4 dl.select dd ul').html(returndata.list);
                    $('.select-city4 dl.select dd ul').attr('style', 'display:none;');
                    $('.select-city4').unbind();
                    $('dt a',$('.select-city4')).unbind();
                    $('ul a',$('.select-city4')).unbind();
                    CityDropdown($('.select-city4'));
                }
            }
        }
    );
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Comment functions
 */
function getIEVersionNumber()
{
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}
// Do add comment action
function addCommentDo()
{
    var removeClick = (navigator.appVersion.match(/MSIE/) && getIEVersionNumber() < 8) ? false : true;
    if (removeClick) $('#frmAddComment a.btn').attr('onclick', '');
    var doStatus = true;
    
    if ($('#comment_author').val() == $('#comment_author').attr('title') || isFieldEmpty('#comment_author')) {
        doStatus = false;
        addCommentShowError('comment_author', frmMsg[1]);
    }
    else {
        if (containsAllowedChars('#comment_author')) {
            addCommentShowOk('comment_author');
        }
        else {
            doStatus = false;
            addCommentShowError('comment_author', frmMsg[0]);
        }
    }
    if ($('#comment_text').val() == $('#comment_text').attr('title') || isFieldEmpty('#comment_text')) {
        doStatus = false;
        addCommentShowError('comment_text', frmMsg[2]);
    }
    else {
        if (containsAllowedChars('#comment_text')) {
            addCommentShowOk('comment_text');
        }
        else {
            doStatus = false;
            addCommentShowError('comment_text', frmMsg[0]);
        }
    }
    
    if (doStatus) {
        $.post(
            domain + "ajax.php",
            "aa=comment_add&ac=" + bCountry + "&al=" + bLang + "&value=" + $('#section_id').val() + "&author=" + $('#comment_author').val() + "&text=" + $('#comment_text').val() + "&rate=" + $('#vote_result').val(),
            function(data) {
                var returndata = JSON.parse(data);
                if (returndata != null && returndata != undefined) {
                    if (parseInt(returndata.status) == 0) {
                        // ok
                        $('#comment_author').val($('#comment_author').attr('title'));
                        $('#comment_text').val($('#comment_text').attr('title'));
                        $('#frmAddComment .success').html(returndata.message);
                        $('#frmAddComment .success').show();
                        addCommentHideIcons('comment_author');
                        addCommentHideIcons('comment_text');
                        $('.vote_list li').each(function() {
                            $(this).removeClass('sel');
                        });
                        $('#vote_result').val('0');
                        loadCommentsList(1);
                    }
                    else {
                        // error
                        if (returndata.field != undefined && returndata.field == 'author')
                        {
                            addCommentShowError('comment_author', returndata.message);
                        }
                        else if (returndata.field != undefined && returndata.field == 'both')
                        {
                            addCommentShowError('comment_author', returndata.message);
                            addCommentShowError('comment_text', returndata.message);
                        }
                        else {
                            addCommentShowError('comment_text', returndata.message);
                        }
                    }
                    if (removeClick) $('#frmAddComment a.btn').attr('onclick', 'addCommentDo();');
                }
            }
        );
    }
    else {
        if (removeClick) $('#frmAddComment a.btn').attr('onclick', 'addCommentDo();');
    }
    return true;
}

// Show add comment error message
function addCommentShowError(field, valText)
{
    // Set the default values if needed
    if (valText === undefined) valText = 'Error!';
    
    // set style
    $('#' + field).parent().parent().removeClass('ok').addClass('error');
    $('#' + field).parent().removeClass('ok').addClass('error');
    if (field == 'comment_author') {
        $('#' + field).parent().next().next().next().next().html(valText);
    }
    else {
        $('#' + field).parent().next().html(valText);
    }
    $('#frmAddComment .success').html('');
    $('#frmAddComment .success').hide();
}

// Show add comment ok message/icon
function addCommentShowOk(field)
{
    $('#' + field).parent().parent().removeClass('error').addClass('ok');
    $('#' + field).parent().removeClass('error').addClass('ok');
    if (field == 'comment_author') {
        $('#' + field).parent().next().next().next().next().html('');
    }
    else {
        $('#' + field).parent().next().html('');
    }
}

// Hide ok/error icons
function addCommentHideIcons(field)
{
    $('#' + field).parent().parent().removeClass('error').removeClass('ok');
    $('#' + field).parent().removeClass('error').removeClass('ok');
    if (field == 'comment_author') {
        $('#' + field).parent().next().next().next().next().html('');
    }
    else {
        $('#' + field).parent().next().html('');
    }
}

// Load comments list
function loadCommentsList(page)
{
    $.post(
        domain + "ajax.php",
        "aa=comment_list&ac=" + bCountry + "&al=" + bLang + "&value=" + $('#section_id').val() + "&page=" + page,
        function(data) {
            var returndata = JSON.parse(data);
            if (returndata != null && returndata != undefined) {
                if (parseInt(returndata.status) == 0) {
                    if (parseInt(returndata.count) > 0) {
                    	$('.no_c_msg').html('');
                        $('.no_c_msg').hide();

                        $('#rate').html(returndata.productRatings);
                        
                        var comm_text = (parseInt(returndata.count) == 1) ? frmMsg[5] : frmMsg[4];
                        $('div.clearfix a#counter').html(returndata.count + ' ' + comm_text);
                        $('.right .comments').html(returndata.list);
                        $('.right .comments').show();
                        if (returndata.pager != '') {
                            $('.right .pagination div').html(returndata.pager);
                            $('.right .pagination').show();
                        }
                    }
                    else {
                        $('.right .comments').html('');
                        $('.right .comments').hide();
                        $('.right .pagination div').html('');
                        $('.right .pagination div').hide();
                        $('.no_c_msg').html(returndata.message);
                        $('.no_c_msg').show();
                    }   
                }
            }
        }
    );
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Subscribe/unsubscribe functions
 */

// Do subscribe action
function subscribeDo()
{
    var doStatus = true;
    
    if ($('#subscribe_email').val() == $('#subscribe_email').attr('title')) {
        doStatus = false;
        subscribeShowError(frmMsg[0]);
    }
    else {
        if (isFieldCorrectLength("#subscribe_email", 5, 50)) {
            doStatus = false;
            subscribeShowError(frmMsg[1]);
        }
        else {
            if (isFieldEmail('#subscribe_email')) {
                doStatus = false;
                subscribeShowError(frmMsg[2]);
            }
        }
    }
    
    if (doStatus) {
        $.post(
            domain + "ajax.php",
            "aa=subscribe&ac=" + bCountry + "&al=" + bLang + "&value=" + $('#subscribe_email').val(),
            function(data) {
                var returndata = JSON.parse(data);
                if (returndata != null && returndata != undefined) {
                    if (parseInt(returndata.status) == 0) { // ok
                        $('#subscribe_email').val($('#subscribe_email').attr('title'));
                        if ($('#newsletterOk').length) {
                            $('#okResult').children().next().children().html(returndata.message);
                            $('#newsletterForm').hide();
                            $('#newsletterOk').show();
                            $('.subscribe .mailing.success .txt div').each(function(){
                                $(this).css({'margin-top': ($(this).parent().height() - $(this).height()) / 2});
                            });
                        }
                        else {
                            $('#frmSubscribe').hide();
                            $('#newsletterStartOk').children().html(returndata.message);
                            $('.mailing').addClass('success');
                            $('#newsletterStartOk').show();
                            $('.mailing .txt div').each(function(){
                                $(this).css({'margin-top': ($(this).parent().height() - $(this).height()) / 2});
                            });
                        }
                    }
                    else { // error
                        subscribeShowError(returndata.message);
                    }
                }
            }
        );
    }
}

// Show subscribe error message
function subscribeShowError(valText)
{
    // Set the default values if needed
    if (valText === undefined) valText = 'Error!';
    
    // Show error
    //alert(valText);
    $('#subscribe_email').parent().removeClass('ok').addClass('error');
    $('#subscribe_email').parent().next().next().next().html(valText);
    $('#subscribe_email').parent().next().next().next().show();
}

// Show subscribe ok
function subscribeShowOk()
{
    $('#subscribe_email').parent().removeClass('error').addClass('ok');
    $('#subscribe_email').parent().next().next().next().html('');
    $('#subscribe_email').parent().next().next().next().hide();
}

// Hide ok/error icons
function subscribeHideIcons()
{
    $('#subscribe_email').parent().removeClass('error').removeClass('ok');
    $('#subscribe_email').parent().next().next().next().html('');
    //$('#subscribe_email').parent().next().next().next().hide();
}

// Do unsubscribe action
function unsubscribeDo()
{
    $('#action').val('unsubscribeDo');
    $('#unsubscribeForm').submit();
    return false;
}

// Cancel unsubscribe action
function unsubscribeCancel()
{
    $('#action').val('unsubscribeCancel');
    $('#unsubscribeForm').submit();
    return false;
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Basket functions
 */
var ajax_anim = false;

// Do product adding to basket
function addToBasketDo(id, count_elem, price)
{
    
    // Set the default count values if no element
    var items_count = 1;
    if (count_elem === undefined || count_elem == '1') {
        items_count = 1;
    }
    // Else get value from textbox element
    else {
        items_count = $("#" + count_elem).val();
    }

    // Set default price if not set
    if (price === undefined) price = 0.00;
    
    // Do tracking
    if (parseInt(gtTracking) == 1) {
        <!--
        _gdeact_koikoqeofu = new Image(1,1);
        _gdeact_koikoqeofu.src='http://gdelv.hit.gemius.pl/_'+(new Date()).getTime()+'/redot.gif?id=nGDrq0xPgGDUhBdjYgjkP9Vp.j51IEcegg1mmyhG6NX.V7';
        //-->
    }
    
    // When on shopping bag form
    if ($('#basket').length > 0 || $('#left_2 .subscribe .content').length > 0) {
        $.ajax({  
            type: "POST",  
            url: domain + "ajax.php",  
            data: {aa: "product_add", ac: bCountry, al: bLang, value: id, count: items_count, price: price},  
            success: function(data) {
                var returndata = JSON.parse(data);
                if (returndata != null && returndata != undefined) {
                    if (parseInt(returndata.status) == 0) {
                        $('.btn_3').attr('style', '');
                        jsRedirect(domain + urlBasket.substring(1));
                    }
                }
            }
        });
    }
    else {
        
        // If animation started previously
        if (ajax_anim) return false;
        else ajax_anim = true;

        // Start animation and product adding to basket
        if (ajax_anim) {

            var productX = $("#product_id_" + id).offset().left;
            var productY = $("#product_id_" + id).offset().top;
            var basketX = $("#headBasket").offset().left - ($('.item_list').length > 0 ? 20 : 0);
            var basketY = $("#headBasket").offset().top;
            var gotoX = basketX - productX;
            var gotoY = basketY - productY;
            var resize = $('.item_list').length > 0 ? 5.5 : 4;
            var newImageWidth = $("#product_id_" + id + " img").width() / resize;
            var newImageHeight = $("#product_id_" + id + " img").height() / resize;

            $("#product_id_" + id + " img")
                .clone()
                .prependTo("#product_id_" + id)
                .css({'position' : 'absolute'})
                .animate({opacity: 1.0}, 100)
                .animate({opacity: 1.0, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 400, function(){
                    
                    $(this).remove();
                    //alert($(this).attr('style'));
                    $.ajax({  
                        type: "POST",  
                        url: domain + "ajax.php",  
                        data: {aa: "product_add", ac: bCountry, al: bLang, value: id, count: items_count, price: price},  
                        success: function(data) {
                            var returndata = JSON.parse(data);
                            if (returndata != null && returndata != undefined) {
                                if (parseInt(returndata.status) == 0) {
                                    $('#bCount').html(returndata.basketCount);
                                    $('#bPrice').html(returndata.basketPrice);
                                    $('.btn_3').attr('style', '');
                                }
                            }
                            ajax_anim = false;
                        }
                    });
                });

        }
    }

    return false;
}

// Change added to basket product count
function changeBasketCount(id, items_count)
{
    // Calculate prices
    var priceItem = parseFloat($('#itemPrice_' + id).val().replace(",", "."));
    var priceTotal = priceItem * items_count;
    priceTotal = priceTotal.toFixed(2);
    
    // Set total price and count
    $('#total_' + id).val(priceTotal);
    $('#count_' + id).val(items_count);
    
    // Calculate total sums
    changeTotalSum();
    
    // Update basket data
    $.post(
        domain + "ajax.php",
        "aa=product_change_count&ac=" + bCountry + "&al=" + bLang + "&value=" + id + "&count=" + items_count + "&price=" + priceItem,
        function(){}
    );
}

// Remove product from basket
function removeFromBasket(id)
{
    // Calculate total sums
    changeTotalSum();
    
    // Update basket data
    $.post(
        domain + "ajax.php",
        "aa=product_remove&ac=" + bCountry + "&al=" + bLang + "&value=" + id,
        function(){}
    );
}

// Remove all products from basket
function basketClear()
{
    $.post(
        domain + "ajax.php",
        "aa=product_remove_all&ac=" + bCountry + "&al=" + bLang,
        function(){
            jsRedirect(urlBasket);
        }
    );
}
    
// Calculate total products sum
function changeTotalSum()
{
    var sum = 0.00;
    var products_count = 0;
    
    $('#bPRoductsList :input').each(function(n, element) {
        if (!$(element).attr("id").search("total_")) {
            var pTotal = parseFloat($(element).val().replace(",", "."));
            pTotal = pTotal.toFixed(2);
            sum = toFixedDecimal(window.Number(sum) + window.Number(pTotal));
            products_count++;
        }
    });
    
    $('#sumpay').html(toFixedDecimal(sum));
    
    if ($('#bonus_discount').val() != '') {
        var bonusDiscount = parseFloat($('#bonus_discount').val().replace(",", "."));
        bonusDiscount = bonusDiscount.toFixed(2);
        var bonusSum = calculateBonusSum(bonusDiscount, sum);
        var newTotalSum = toFixedDecimal(window.Number(sum) - window.Number(bonusSum));
        var freeSum = 0;
        if (newTotalSum < 0) {
            freeSum = newTotalSum*(-1);
            newTotalSum = 0.00;
        }
        $('#sumdiscount').html(bonusSum);
        $('#sumpay').html(newTotalSum);
        $('.tools').show();
        $('#bonusLine').show();
        $('#basket').removeClass('no_bonus');
    }
    
    if (products_count == 0) {
        $('#bPRoductsList').hide();
        $('#frmBonus').hide();
        $('#tblResult').hide();
        $('.tools').hide();
        $('#btnNextStep').hide();
        $('#bEmpty').show();
    }
}

// Check user entered bonuse code value
function checkBonusDiscount(param)
{
    
    // Set default param value if not set
    if (param === undefined) param = '';
    
    // Get bonuse code value
    if ($('#bonus_code').val() == $('#bonus_code').attr('title')) $('#bonus_code').val("");
    var bonus_code = $('#bonus_code').val();
    
    // Do checking
    if (jQuery.trim(bonus_code) != "") {
        bonusErrorHide();
        $.post(
            domain + "ajax.php",
            "aa=check_bonus_code&ac=" + bCountry + "&al=" + bLang + "&value=" + bonus_code,
            function(data) {
                var returndata = JSON.parse(data);
                if (returndata != null && returndata != undefined) {
                    // If code valid, calculate new total sums
                    if (parseInt(returndata.status) == 0) {
                        $('#bonus_discount').val(returndata.bonusDiscount);
                        bonusErrorHide();
                        changeTotalSum();
                        $('.remove').show();
                        if (param == 'confirm') jsRedirect($('#confirm_url').val());
                    }
                    // Else show error message
                    else {
                        $('#bonus_discount').val('');
                        $('#bonusLine').hide();
                        $('#basket').addClass('no_bonus');
                        $('.remove').hide();
                        changeTotalSum();
                        bonusErrorShow(returndata.message);
                    }
                }
            }
        );
    }
    else {
        if (param == 'confirm') jsRedirect($('#confirm_url').val());
        else {
            if (param == 'blr') {
                $('#bonus_code').val($('#bonus_code').attr('title'));
                return false;
            }
            else bonusErrorShow(frmMsg[0]);
        }
    }
}

// Calculate bonus sum
function calculateBonusSum(discount, totalSum)
{
    var bonusSum = toFixedDecimal((window.Number(totalSum)/100)*window.Number(discount));
    return bonusSum;
}

// Remove bonuse code
function removeBonuseCode()
{
    var bonus_code = $('#bonus_code').val();
    bonusErrorHide();
    $.post(
        domain + "ajax.php",
        "aa=remove_bonus_code&ac=" + bCountry + "&al=" + bLang + "&value=" + bonus_code,
        function(data) {
            var returndata = JSON.parse(data);
            if (returndata != null && returndata != undefined) {
                // If code valid, calculate new total sums
                if (parseInt(returndata.status) == 0) {
                    $('#bonus_discount').val('');
                    $('#bonus_code').val($('#bonus_code').attr('title'));
                    $('#bonusLine').hide();
                    $('#basket').addClass('no_bonus');
                    $('.remove').hide();
                    changeTotalSum();
                }
            }
        }
    );
}

// Show bonus form error on basket form
function bonusErrorShow(msg)
{
    $('#frmBonus').addClass('error');
    $('#frmBonus .bonMsg').html(msg);
}

// Hide bonus form error on basket form
function bonusErrorHide()
{
    $('#frmBonus').removeClass('error');
    $('#frmBonus .bonMsg').html('');
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Order data functions
 */

// Validate data and submit form
function checkOrderData()
{
    
    var bigErrorMsg = '';
    
    setBillingAsDelivery();

    var personType = $('input:radio[name=personType]:checked').val();
    var errorsCount = 0;
    
    // Validate order form field on blur
    $('#complOrderForm :input').each(function() {
        if ($(this).attr('type') == 'text') {
            
            // Set field values
            var fieldName = $(this).attr('id');
            var validationStatus = true;
            
            // Has validation rules
            if (jQuery.trim($(this).attr('class')) != '') {
                jQuery.each(jQuery.trim($(this).attr('class')).split(" "), function(i, validate) {
                    if (validationStatus) {
                        if (containsAllowedChars('#'+fieldName)) {
                            if (validate == 'required') {
                                if (
                                    (personType == 'private' && (fieldName == 'pName' || fieldName == 'pPhone' || fieldName == 'pEmail')) ||
                                    (personType == 'legal' && (fieldName == 'lCompany' || fieldName == 'lRegNo' || fieldName == 'lPhone' || fieldName == 'lEmail')) || 
                                    (fieldName == 'dZip' || fieldName == 'dCity' || fieldName == 'dCountry' || fieldName == 'dAddress')
                                ) {
                                    if (!isFieldEmpty('#'+fieldName)) {
                                        orderOkShow(fieldName);
                                    }
                                    else {
                                        orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                        bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                        validationStatus = false;
                                        errorsCount++;
                                    }
                                }
                                else if (fieldName == 'bZip' || fieldName == 'bCity' || fieldName == 'bCountry' || fieldName == 'bAddress') {
                                    if ($('#sameAsDelivery').is(':checked')) {
                                        // do not check is same as delivery
                                    }
                                    else {
                                        if (!isFieldEmpty('#'+fieldName)) {
                                            orderOkShow(fieldName);
                                        }
                                        else {
                                            orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                            bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                            validationStatus = false;
                                            errorsCount++;
                                        }
                                    }
                                }
                            }
                            else if (validate == 'phone') {
                                if (
                                    (personType == 'private' && (fieldName == 'pName' || fieldName == 'pPhone' || fieldName == 'pEmail')) ||
                                    (personType == 'legal' && (fieldName == 'lCompany' || fieldName == 'lRegNo' || fieldName == 'lPhone' || fieldName == 'lEmail')) || 
                                    (fieldName == 'bZip' || fieldName == 'dZip' || fieldName == 'bCity' || fieldName == 'dCity' || fieldName == 'bCountry' || fieldName == 'dCountry' || fieldName == 'bAddress' || fieldName == 'dAddress')
                                ) {
                                    if (isFieldNumbers('#'+fieldName)) {
                                        orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                        bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                        validationStatus = false;
                                        errorsCount++;
                                    }
                                    else {
                                        orderOkShow(fieldName);
                                    }
                                }
                            }
                            else if (validate == 'email') {
                                if (
                                    (personType == 'private' && (fieldName == 'pName' || fieldName == 'pPhone' || fieldName == 'pEmail')) ||
                                    (personType == 'legal' && (fieldName == 'lCompany' || fieldName == 'lRegNo' || fieldName == 'lPhone' || fieldName == 'lEmail')) || 
                                    (fieldName == 'bZip' || fieldName == 'dZip' || fieldName == 'bCity' || fieldName == 'dCity' || fieldName == 'bCountry' || fieldName == 'dCountry' || fieldName == 'bAddress' || fieldName == 'dAddress')
                                ) {
                                    if (!isFieldCorrectLength('#'+fieldName, 5, 50)) {
                                        if (isFieldEmail('#'+fieldName)) {
                                            orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                            bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                            validationStatus = false;
                                            errorsCount++;
                                        }
                                        else {
                                            orderOkShow(fieldName);
                                        }
                                    }
                                    else {
                                        orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, 'length'));
                                        bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                        validationStatus = false;
                                        errorsCount++;
                                    }
                                }
                            }
                            else if (validate == 'regno') {
                                if (
                                    (personType == 'private' && (fieldName == 'pName' || fieldName == 'pPhone' || fieldName == 'pEmail')) ||
                                    (personType == 'legal' && (fieldName == 'lCompany' || fieldName == 'lRegNo' || fieldName == 'lPhone' || fieldName == 'lEmail')) || 
                                    (fieldName == 'bZip' || fieldName == 'dZip' || fieldName == 'bCity' || fieldName == 'dCity' || fieldName == 'bCountry' || fieldName == 'dCountry' || fieldName == 'bAddress' || fieldName == 'dAddress')
                                ) {
                                    if (!isFieldCorrectLength('#'+fieldName, 9, 9) || !isFieldCorrectLength('#'+fieldName, 12, 12)) {
                                        orderOkShow(fieldName);
                                    }
                                    else {
                                        orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                        bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                        validationStatus = false;
                                        errorsCount++;
                                    }
                                }
                            }
                            else if (validate == 'zip') {
                                if (
                                    (personType == 'private' && (fieldName == 'pName' || fieldName == 'pPhone' || fieldName == 'pEmail')) ||
                                    (personType == 'legal' && (fieldName == 'lCompany' || fieldName == 'lRegNo' || fieldName == 'lPhone' || fieldName == 'lEmail')) || 
                                    (fieldName == 'dZip' || fieldName == 'dCity' || fieldName == 'dCountry' || fieldName == 'dAddress')
                                ) {
                                    if (!isFieldCorrectLength('#'+fieldName, 4, 10)) {
                                        orderOkShow(fieldName);
                                    }
                                    else {
                                        orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                        bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                        validationStatus = false;
                                        errorsCount++;
                                    }
                                }
                                else if (fieldName == 'bZip' || fieldName == 'bCity' || fieldName == 'bCountry' || fieldName == 'bAddress') {
                                    if ($('#sameAsDelivery').is(':checked')) {
                                        // do not check is same as delivery
                                    }
                                    else {
                                        if (!isFieldEmpty('#'+fieldName)) {
                                            orderOkShow(fieldName);
                                        }
                                        else {
                                            orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                            bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + getOrderFormErrorMessage(fieldName, validate) + '</li>';
                                            validationStatus = false;
                                            errorsCount++;
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            orderErrorShow(fieldName, frmMsg[14]);
                            bigErrorMsg += '<li id="br'+fieldName+'">-&nbsp; ' + frmMsg[14] + '</li>';
                            validationStatus = false;
                            errorsCount++;
                        }
                        return validationStatus;
                    }
                });
            }
            // Do not have validation rules
            else {
                if (!isFieldEmpty('#'+fieldName)) orderOkShow(fieldName);
            }
            
        }
    });
    
    // textareas
    if (personType == 'private') {
        if (!isFieldEmpty('#pNotes')) orderOkShow('pNotes');
    }
    else if (personType == 'legal') {
        if (!isFieldEmpty('#lNotes')) orderOkShow('lNotes');
    }
    
    // If no errors submit form
    if (errorsCount == 0) {
        if (parseInt(gtTracking) == 1) {
            <!--
            _gdeact_xopqboosep = new Image(1,1);
            _gdeact_xopqboosep.src='http://gdelv.hit.gemius.pl/_'+(new Date()).getTime()+'/redot.gif?id=AkTlD_OJJbPAzP5oD8Og7NTJXkd14AdPrOOWVM1UADP.V7';
            //-->
        }
        $('#bfErrMsg').hide();
        $('#bfErrMsg ul').html('');
        $('#frmType').val('createOrder');
        $('#complOrderForm').submit();
    }
    else {
        $('#bfErrMsg ul').html(bigErrorMsg);
        $('#bfErrMsg').show();
        return false;
    }
}

// Show/Hide physical/legal person type form
function showOrdForm(type)
{
    if (parseInt(type) == 2) {
        $('#pName').parent().parent().hide();
        $('#pPhone').parent().parent().hide();
        $('#pEmail').parent().parent().hide();
        $('#pNotes').parent().parent().hide();
        $('#lCompany').parent().parent().show();
        $('#lRegNo').parent().parent().show();
        $('#lVatNo').parent().parent().show();
        $('#lAddress').parent().parent().show();
        $('#lPhone').parent().parent().show();
        $('#lEmail').parent().parent().show();
        $('#lNotes').parent().parent().show();
    }
    else {
        $('#lCompany').parent().parent().hide();
        $('#lRegNo').parent().parent().hide();
        $('#lVatNo').parent().parent().hide();
        $('#lAddress').parent().parent().hide();
        $('#lPhone').parent().parent().hide();
        $('#lEmail').parent().parent().hide();
        $('#lNotes').parent().parent().hide();
        $('#pName').parent().parent().show();
        $('#pPhone').parent().parent().show();
        $('#pEmail').parent().parent().show();
        $('#pNotes').parent().parent().show();
    }
}

// Show/Hide billing address fields
function showBillingAddressForm()
{
    $('.dati .labi').each(function(){
        if ($('#sameAsDelivery').is(':checked')) {
            $(this).hide();
        }
        else {
            $(this).show();
        }
    });
    setBillingAsDelivery();
}

// Copy delivery address values to billing address, if need
function setBillingAsDelivery()
{
    if ($('#sameAsDelivery').is(':checked')) {
        $('#bAddress').val($('#dAddress').val());
        $('.select-city .select dt a span').html($('.select-city2 .select dt a span').html());
        $('#bCountry').val($('#dCountry').val());
        $('#bCity').val($('#dCity').val());
        $('#bZip').val($('#dZip').val());
    }
}

// Show order form ok
function orderOkShow(field)
{
    $('#' + field).parent().parent().removeClass('form-error').addClass('form-ok');
    $('#' + field).parent().next().next().html('');
    if ($('#br' + field)) $('#br' + field).remove();
    if ($('#bfErrMsg ul').html() == '') $('#bfErrMsg').hide();
}

// Show order form error
function orderErrorShow(field, msg)
{
    $('#' + field).parent().parent().removeClass('form-ok').addClass('form-error');
    $('#' + field).parent().next().next().html(msg);
}

// Hide order form ok and error style
function orderBothIcosHide(field)
{
    $('#' + field).parent().parent().removeClass('form-error').removeClass('form-ok');
    $('#' + field).parent().next().next().html('');
}

// Get order form validation error message
function getOrderFormErrorMessage(field, type)
{
    if (type === undefined) type = '';
    var result = '';
    switch (field) {
        case 'pName':
            result = frmMsg[0];
            break;
        case 'pPhone':
        case 'lPhone':
            result = frmMsg[1];
            break;
        case 'pEmail':
        case 'lEmail':
            if (type == 'required' || type == 'length') {
                result = frmMsg[2];
            }
            else if (type == 'format') {
                result = frmMsg[3];
            }
            else if (type == 'email') {
                result = frmMsg[4];
            }
            break;
        case 'lCompany':
            result = frmMsg[5];
            break;
        case 'lRegNo':
            if (type == 'regno') {
                result = frmMsg[7];
            }
            else {
                result = frmMsg[6];
            }
            break;
        case 'dAddress':
        case 'bAddress':
            result = frmMsg[9];
            break;
        case 'dCountry':
        case 'bCountry':
            result = frmMsg[10];
            break;
        case 'dCity':
        case 'bCity':
            result = frmMsg[11];
            break;
        case 'dZip':
        case 'bZip':
            if (type == 'zip') {
                result = frmMsg[13];
            }
            else {
                result = frmMsg[12];
            }
            break;
    }
    return result;
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Various form functions
 */

// Save form values to session, so if user goes to another page and returns back we will output entered values
function rememberFormValues(frmName)
{
    
    $.post(
        domain + "ajax.php",
        "aa=remember_data&ac=" + bCountry + "&al=" + bLang + "&form=" + frmName +
        "&personType=" + $('input[name="personType"]:checked').val() + 
        "&pName=" + (containsAllowedChars('#pName') ? $("#pName").val() : '') + 
        "&pPhone=" + (containsAllowedChars('#pPhone') ? $("#pPhone").val() : '') + 
        "&pEmail=" +(containsAllowedChars('#pEmail') ? $("#pEmail").val() : '') + 
        "&pNotes=" + (containsAllowedChars('#pNotes') ? $("#pNotes").val() : '') + 
        "&lCompany=" + (containsAllowedChars('#lCompany') ? $("#lCompany").val() : '') + 
        "&lRegNo=" + (containsAllowedChars('#lRegNo') ? $("#lRegNo").val() : '') + 
        "&lVatNo=" + (containsAllowedChars('#lVatNo') ? $("#lVatNo").val() : '') + 
        "&lAddress=" + (containsAllowedChars('#lAddress') ? $("#lAddress").val() : '') + 
        "&lPhone=" + (containsAllowedChars('#lPhone') ? $("#lPhone").val() : '') + 
        "&lEmail=" + (containsAllowedChars('#lEmail') ? $("#lEmail").val() : '') + 
        "&lNotes=" + (containsAllowedChars('#lNotes') ? $("#lNotes").val() : '') + 
        "&dAddress=" + (containsAllowedChars('#dAddress') ? $("#dAddress").val() : '') + 
        "&dCountry=" + (containsAllowedChars('#dCountry') ? $("#dCountry").val() : '') + 
        "&dCity=" + (containsAllowedChars('#dCity') ? $("#dCity").val() : '') + 
        "&dZip=" + (containsAllowedChars('#dZip') ? $("#dZip").val() : '') + 
        "&sameAsDelivery=" + ($('#sameAsDelivery').is(':checked') ? 1 : 0) + 
        "&bAddress=" + (containsAllowedChars('#bAddress') ? $("#bAddress").val() : '') + 
        "&bCountry=" + (containsAllowedChars('#bCountry') ? $("#bCountry").val() : '') + 
        "&bCity=" + (containsAllowedChars('#bCity') ? $("#bCity").val() : '') + 
        "&bZip=" + (containsAllowedChars('#bZip') ? $("#bZip").val() : '') + 
        "&payType=" + $('input[name="payType"]:checked').val(),
        function(){}
    );
}

// Clear form 
function clearFormElements(frmName)
{
    $('#' + frmName + ' :input').each(function(n, element) {
        $(element).val('');
    });
}

////////////////////////////////////////////////////////////////////////////////

var prodImgInterval = 1;

// STARTS and Resets the loop if any
function startProdImgLoop()
{
    setInterval("changeProdImg()", 3000);
}

function changeProdImg()
{
    if (prodImgInterval > 0) {
        //alert($("ul.thumbs li.sel").html());
        var src = $("ul.thumbs li.sel").next().children().children().attr('src');
        var alt = $("ul.thumbs li.sel").next().children().children().attr('alt');
        //alert('next image src: ' + src + ' and alt: ' + alt);
        if (src === undefined || alt === undefined) {
            src = $("ul.thumbs li:first-child").children().children().attr('src');
            alt = $("ul.thumbs li:first-child").children().children().attr('alt');
            //alert('next image src: ' + src + ' and alt: ' + alt);
            $("ul.thumbs li").each(function() {
                $(this).removeClass('sel');
            });
            $("ul.thumbs li:first-child").addClass('sel');
        }
        else {
            $("ul.thumbs li.sel").removeClass('sel');
            $("ul.thumbs li").each(function() {
                if ($(this).children().children().attr('src') == src) {
                    $(this).addClass('sel');
                }
            });
        }
        $('#bigImage').attr('src', src.replace('/thumbs/','/big/')).attr('alt', alt);
    }
}

////////////////////////////////////////////////////////////////////////////////

/**
 * Start actions after page is loaded
 */

$(document).ready(function(){

    // Hide/Show shop item panel with addresses
    $('.contact .places > ul ul a, .contact .places > ul ul').click(function(e) {e.stopPropagation();});
    $('.contact .places > ul > li').click(function(e) {
        if ($(this).hasClass('active') == true) {
            $(this).removeClass('active');
            $(this).find('ul').slideUp();
        }
        else {
            $(this).addClass('active');
            $(this).find('ul').slideDown();
        }
    });
		
    // Contacts form
    if ($('.c_form').length){
        
        // Remove ok/error on contact form field focus
        $('.c_form :input').focus(function() {
            if ($(this).val() == $(this).attr('title')) $(this).val("");
            if ($(this).attr('type') == 'text') mailHideIcons($(this).attr('id'));
        }).blur(function(){
            if ($(this).val() == "") $(this).val($(this).attr('title'));
            if ($(this).attr('id') == 'fullname') {
                if ($('#fullname').val() == $('#fullname').attr('title') || isFieldEmpty('#fullname')) {
                    //mailShowError('fullname', frmMsg[0]);
                }
                else {
                    mailShowOk('fullname');
                }
            }
            else if ($(this).attr('id') == 'phone') {
                if (!isFieldEmpty('#phone') && $('#phone').val() != $('#phone').attr('title')) {
                    if (isFieldNumbers("input[name=phone]")) {
                        //mailShowError("phone", frmMsg[1]);
                    }
                    else {
                        mailShowOk("phone");
                    }
                }
            }
            else if ($(this).attr('id') == 'email') {
                if ($('#email').val() == $('#email').attr('title') || isFieldEmpty('#email')) {
                    //mailShowError('email', frmMsg[2]);
                }
                else {
                    if (isFieldCorrectLength("#email", 5, 50)) {
                        mailShowError('email', frmMsg[3]);
                    }
                    else {
                        if (isFieldEmail("#email")) {
                            mailShowError('email', frmMsg[4]);
                        }
                        else {
                            mailShowOk('email');
                        }
                    }
                }
            }
        });
        $('.c_form textarea').focus(function() {
            if ($(this).val() == $(this).attr('title')) $(this).val("");
            mailHideIcons($(this).attr('id'));
        }).blur(function(){
            if ($(this).val() == "") $(this).val($(this).attr('title'));
            if ($(this).attr('id') == 'question') {
                if ($('#question').val() == $('#question').attr('title') || isFieldEmpty('#question')) {
                    //mailShowError('question', frmMsg[5]);
                }
                else {
                    mailShowOk('question');
                }
            }
        });

    }

    // Load big image on thumb click
    if ($('ul.thumbs').length) {
        
        // Manual change
        $('ul.thumbs li a').click(function() {
            prodImgInterval = 0;
            $("ul.thumbs li").each(function() {
                $(this).removeClass('sel');
            });
            $('#bigImage')
                .attr('src', $(this).children().attr('src').replace('/thumbs/','/big/'))
                .attr('alt', $(this).children().attr('alt'));
            $(this).parent().addClass('sel');
        });
        
        // If need do auto img change
        if ($("ul.thumbs").children().length > 1) {
            startProdImgLoop();
        }
    }
    
    // Load comments list in product detaols view
    if ($('.right .comments').length) {
        loadCommentsList(1);
    }
    
    // Newsletter form
    if ($('div.mailing').length) {
        $('div.mailing input#subscribe_email').focus(function() {
            if ($(this).val() == $(this).attr('title')) $(this).val("");
            subscribeHideIcons();
        }).blur(function(){
            if ($(this).val() == "") $(this).val($(this).attr('title'));
            if ($(this).val() != $(this).attr('title')) {
                if (isFieldCorrectLength("#subscribe_email", 5, 50)) {
                    subscribeShowError(frmMsg[1]);
                }
                else {
                    if (isFieldEmail('#subscribe_email')) {
                        subscribeShowError(frmMsg[2]);
                    }
                    else {
                        subscribeShowOk();
                    }
                }
            }
        }).keyup(function(e) {
            if (!e) var e = window.event;
            var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : null;
            if (keyCode == 13) subscribeDo();
            return false;
        });
    }
    
    // Bonuse code form
    if ($('form#frmBonus').length) {
        $('form#frmBonus input#bonus_code').focus(function() {
            if ($(this).val() == $(this).attr('title')) $(this).val("");
            bonusErrorHide();
        }).keyup(function(e) {
            if (!e) var e = window.event;
            var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : null;
            if (keyCode == 13) checkBonusDiscount('confirm');
            return false;
        });/*.blur(function(){
            if ($(this).val() == "") $(this).val($(this).attr('title'));
            if ($(this).val() == $(this).attr('title')) {
                bonusErrorShow(frmMsg[0]);
            }
        })*/
    }
    
    // Disable form submit on enter
    $('form#frmSubscribe, form#frmBonus').submit(function() {
        return false;
    });

    // Remove ok/error on order form field focus
    $('#complOrderForm :input').focus(function() {
        if ($(this).attr('type') == 'text') {
            orderBothIcosHide($(this).attr('id'));
        }
    });
    $('#complOrderForm .textarea textarea').focus(function() {
        orderBothIcosHide($(this).attr('id'));
    });
    
    // Auto payment form submit
    if ($("#paymentForm").length) {
        $("#paymentForm").submit();
    }
    
    // Validate order form field on blur
    $('#complOrderForm .textarea textarea').blur(function() {
        if (!isFieldEmpty('#' + $(this).attr('id'))) orderOkShow($(this).attr('id'));
    });
    $('#complOrderForm :input').blur(function() {
        if ($(this).attr('type') == 'text') {
            
            // Set field values
            var fieldName = $(this).attr('id');
            //var fieldValue = $(this).val();
            var css = $('#' + fieldName).parent().attr('class').replace("-ok", "").replace("-error", "");
            var validationStatus = true;
            
            // Has validation rules
            if (jQuery.trim($(this).attr('class')) != '') {
                jQuery.each(jQuery.trim($(this).attr('class')).split(" "), function(i, validate) {
                    if (validationStatus) {
                        if (containsAllowedChars('#'+fieldName)) {
                            if (validate == 'required') {
                                if (!isFieldEmpty('#'+fieldName)) {
                                    orderOkShow(fieldName);
                                }
                                else {
                                    orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                    validationStatus = false;
                                }
                            }
                            else if (validate == 'phone') {
                                if (isFieldNumbers('#'+fieldName)) {
                                    orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                    validationStatus = false;
                                }
                                else {
                                    orderOkShow(fieldName);
                                }
                            }
                            else if (validate == 'email') {
                                if (!isFieldCorrectLength('#'+fieldName, 5, 50)) {
                                    if (isFieldEmail('#'+fieldName)) {
                                        orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                        validationStatus = false;
                                    }
                                    else {
                                        orderOkShow(fieldName);
                                    }
                                }
                                else {
                                    orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, 'length'));
                                    validationStatus = false;
                                }
                            }
                            else if (validate == 'regno') {
                                if (!isFieldCorrectLength('#'+fieldName, 9, 9) || !isFieldCorrectLength('#'+fieldName, 12, 12)) {
                                    orderOkShow(fieldName);
                                }
                                else {
                                    orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                    validationStatus = false;
                                }
                            }
                            else if (validate == 'zip') {
                                if (!isFieldCorrectLength('#'+fieldName, 4, 10)) {
                                    orderOkShow(fieldName);
                                }
                                else {
                                    orderErrorShow(fieldName, getOrderFormErrorMessage(fieldName, validate));
                                    validationStatus = false;
                                }
                            }
                        }
                        else {
                            orderErrorShow(fieldName, frmMsg[14]);
                            validationStatus = false;
                        }
                        return validationStatus;
                    }
                });
            }
            // Do not have validation rules
            else {
                if (!isFieldEmpty('#'+fieldName)) orderOkShow(fieldName, css);
            }
            
            // Save entered data
            rememberFormValues('complOrderForm');
            
        }
    });

});

