var request_url= '/index.php';

$(document).ready(function() {
    //$('#alert_text').html('<br /><b>ВНИМАНИЕ! <br /><font color="red">Да, сегодня 29 декабря и мы все еще принимаем заказы на доставку курьером по г.Москва на завтра 30 декабря! </font></b><br /><br /><b>Многие покупатели не выкупают свои заказы на праздники, так как не уверены, что посылка придет вовремя. <br /><br />В связи с этим с 15 декабря и до окончания новогодних праздников все заказы по почте, будут отправляться только по полной предоплате.<br /><br />Сделать предоплату созданного заказа можно в разделе <a href="http://www.supermaika.ru/payment/">"Оплатить заказ"</a>.</b><br /><br /></b>'); 
    //$("#main_menu").mouseover(function(){
        //$("#main_menu").lavaLamp({ fx: "linear", speed: 700});    
    //});
    //$('ul.main_menu').lavaLamp({ fx: "jswing", speed: 100, homeTop:10, homeLeft:-100, homeHeight: 91, returnHome:true });
    $('ul.main_menu').children('li:not(.spacer)').each(function(){ 
        $(this).mouseover(function(){
            $(this).css({'background-image':'url(/images/menu-hover-dark.png)', backgroundPosition: '50% 20px'}); 
        });
        $(this).mouseout(function(){
            $(this).css({'background':'none'}); 
        });
    });
    $('.rating_div').css('display', 'block');
    if($('#categoryItemsDiv').length>0)
    {
        h1=$('#categoryItemsDiv').height();
        h2=$('#categoryTextDiv').height();
        h_total=h1+h2;
        $('#categoryMainDiv').height(h_total);
        //alert($('body').height());
    }
    
    $(".tip_trigger").hover(function(){
        tip = $(this).find('.tip');
        tip.show(); //Show tooltip
    }, function() {
        tip.hide(); //Hide tooltip
    }).mousemove(function(e) {
        var mousex = e.pageX + 20; //Get X coodrinates
        var mousey = e.pageY + 20; //Get Y coordinates
        var tipWidth = tip.width(); //Find width of tooltip
        var tipHeight = tip.height(); //Find height of tooltip

        //Distance of element from the right edge of viewport
        var tipVisX = $(window).width() - (mousex + tipWidth);
        //Distance of element from the bottom of viewport
        var tipVisY = $(window).height() - (mousey + tipHeight);

        if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
            mousex = e.pageX - tipWidth - 20;
        } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
            mousey = e.pageY - tipHeight - 20;
        }
        //Absolute position the tooltip according to mouse position
        tip.css({  top: mousey, left: mousex });
    });
    //setTimeout(function(){getNewBlock(1);}, 1000);
    getNewBlock(1);
   if (typeof saveGraphicsFromFlash == 'function' && GEN_PREVIEW) {
setTimeout(function(){saveGraphicsFromFlash(PRODUCT_ID+'|'+PREVIEW_SIZE);}, 2500);
 }
 
 $("a.fancybox").fancybox({
        'transitionIn'    :    'elastic',
        'transitionOut'    :    'elastic',
        'speedIn'        :    600, 
        'speedOut'        :    200 
    });
    
    $("#search_form_input").autocomplete("/index.php", {
        width: 260,
        selectFirst: false
    });
     
});

function getNewBlock(resetPointer)
{
    $.ajax({
           type: "POST",
           url: '/pages/refresh.php',
           data: 'lastId=0&count=4&reset='+resetPointer,
           dataType: "text",
           success: function(data){
               if($('#newBlock').is(':visible'))
               {
                    $('#newBlock').prepend(data);   
               }
               else
               {
                $('#newBlock').html(data)
                              .show();
               }
			   $('.jLoupe, .jloupe').jloupe();   //  Активируем лупу на вновь загруженых макетах
               //$('#newBlock').find('.cloud-zoom').CloudZoom();
           },
           error:function(XMLHttpRequest, textStatus, errorThrown){
               if(resetPointer==0)
                alert('Ошибка! Попробуйте позже.');
               //alert(XMLHttpRequest + '|' + textStatus +  '|' + errorThrown);
           }
         });        
}

function recalcTotal()
{
    var total=0;
    $('[id^="cart_item_quantity_"]').each(function(index){
        quantity=0;
        price=0;
        quantity=parseInt($('#cart_item_quantity_'+index).val());    
        price=parseInt($('#cart_item_price_'+index).val());    
        $('#cart_item_cur_price_'+index).html(quantity*price);
        total+=(quantity*price);
    });
    $('#cart_total_cell > font > b').html(total);
}

function update_cart_quantity(id, quantity)
{
    if(quantity>0)
    {
        $.ajax({
           type: "GET",
           url: '/pages/cart.php',
           data: 'ajax=1&item_id='+id+'&quantity='+quantity,
           dataType: "text",
           success: function(data){
                recalcTotal();            
           },
           error:function(XMLHttpRequest, textStatus, errorThrown){
               alert(XMLHttpRequest + '|' + textStatus +  '|' + errorThrown);
           }
         });    
    }
}

function open_window(link,w,h) //opens new window
{
    var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
    newWin = window.open("popup.php?target="+link,'newWin',win);
    newWin.focus();
}
function open_windowt(link,w,h,path) //opens new window
{
    var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
    newWin = window.open(path+"popup.php?target="+link,'newWin',win);
    newWin.focus();
}
function open_windowf(link,w,h) //opens new window
{
    var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
    newWin = window.open("http://"+location.host+"/popup.php?target="+link,'newWin',win);
    newWin.focus();
}
function open_windowgp(link,w,h) //opens new window
{
    var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
    newWin = window.open(link,'newWin',win);
    newWin.focus();
}


function changeBarover (dd, dq)
{
	document.getElementById(dd).style.backgroundColor = '#eeeeee';
	document.getElementById(dq).style.color =  '#000000';
}
function changeBarout (dd,dq)
{
	document.getElementById(dd).style.backgroundColor = '#60bd25';
	document.getElementById(dq).style.color =  '#24211d';
}

function droptext (object)
{
	object = document.getElementById (object);
	if ( !object.style )
	{
		return false;
	}

	if( object.style.display == 'none' )
	{
		object.style.display = '';
	}
	else
	{
		object.style.display = 'none';
	}
}





function comment_add_form()
{
    if ('block' != $("#comment_add_form").attr('display'))
        $("#comment_add_form").fadeIn("slow");
        else $("#comment_add_form").fadeOut("slow");
}








function link_click(url){
    // 'http://supermaika.ru/' + 
    //alert(base64_decode(url));
    location.href = base64_decode(url);
}

function base64_decode (data) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data += '';
 
    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
 
        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
 
        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);
 
    return dec;
}


function utf8_decode ( str_data ) {

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}

/*
function gopoll()
{
    var answer = $('#poll_form input:radio:checked').val();

    $.get(request_url, {ajax : 'true', module : 'poll', view : tovote, answer : answer }, function(){
        $("#minicart").load("/?ajax=true&module=poll&view=tovote");
    });
}*/

function online()
{
    // Отправляем запрос для учета пользователя онлайн
    $.get(request_url, {ajax : 'true', action : 'get_users_online', view : 'ajax' }, function(data){
        $("#online_qty").html(data);
    });
}








// Самодельная футболка ////////////////////////////////////////////////////////////
var own = new Array;

own['str_number'] = new Array;
own['str_number']['front'] = new Array;
own['str_number']['front']['text'] =  1; // следующий номер для строки спереди
own['str_number']['front']['image'] =  1; // следующий номер для строки спереди

own['str_number']['back'] = new Array;
own['str_number']['front']['text'] = 1; // следующий номер для строки сзади
own['str_number']['front']['image'] = 1; // следующий номер для строки сзади

//own['type'] = new Array;
//own['type']['front'] = 'text'; // тип нанесения спереди
//own['type']['back'] = 'text'; // тип нанесения сзади

//own['price_sum'] = 0;
own['price_sum_front_text'] = 0;
own['price_sum_front_image'] = 0;
own['price_sum_back_text'] = 0;
own['price_sum_back_image'] = 0;
own['price_both_side'] = 0;



function own_side(side)
{
    if ($('input[id='+side+'_checkbox]:checkbox').attr('checked'))
    {
        $("#"+side).fadeIn('slow'); //front_text
    }
    else
    {
        $("#"+side).fadeOut('fast'); //front_text
    }

    own_price_count();
}


function own_check_type(side, type)
{
    /*var typee = $('select[@name=specie_id] option:selected').attr('value');*/
    //var type = $('input[name='+side+'_type]:checkbox:checked').attr('value');
    //if ('image' == type) var type2 = 'text'; else var type2 = 'image'; // опеределяем противоположный тип чтобы скрыть

    var res = $('input[name='+side+'_'+type+']:checkbox').attr('checked');
    if ('checked' == res)
    {
        own['str_number'][side][type] = 1; // сбрасываем счетчик строк
        own['price_sum_'+side+'_'+type] = 0; // сбрасываем счетчик цены
        // удаляем весь контент
        $('#'+side+'_'+type+'_content').html('');
        // добавляем код строки
        add_str(side, type);
        $("#"+side+'_'+type+'_content').fadeIn('slow');
    }
    else
    {
        $("#"+side+'_'+type+'_content').fadeOut('slow', function(){
            $('#'+side+'_'+type+'_content').html('');
        });
        own['str_number'][side][type] = 1; // сбрасываем счетчик строк
        own['price_sum_'+side+'_'+type] = 0; // сбрасываем счетчик цены
    }

    own_price_count();
}

// добавление строки (везде)
function add_str(side, type)
{
    $('#'+side+'_'+type+'_content_str_'+(own['str_number'][side][type]-1)+'_link').attr('style', 'display: none'); // скрываем ссылку добавить строку на которую нажали

    // получаем html код добавляемой строки нужного типа(текст / изображение)
    var html = $('#sample_'+type).html();
    
    // заменяем переменные
    html = str_replace('SIDE', side, html);
    html = str_replace('X', own['str_number'][side][type], html);

    // добавляем строку
    $('#'+side+'_'+type+'_content').append( html );
    //if ('image' == own['type'][side]) $('#'+side+'_image_content_str_'+own['str_number'][side]+'_input').attr('style', 'width: 40px;');

    own['str_number'][side][type] = own['str_number'][side][type] + 1;
}

function check_input(side, type, x)
{
    var value = $('#'+side+'_'+type+'_content_str_'+x+'_input').attr('value');

    if ('' == value)
        $('#'+side+'_'+type+'_content_str_'+x+'_price').html('0');
        else $('#'+side+'_'+type+'_content_str_'+x+'_price').html(own['price_add'][type]);

    own_price_count();
}

// пересчитывает стоимость заказа
function own_price_count()
{
    own['price_sum_front_text'] = 0;
    for (var i = 1; i <= own['str_number']['front']['text']; i++)
    {
        own['price_sum_front_text'] = $('#front_text_content_str_'+i+'_price').html()*1 + own['price_sum_front_text'];
    }
    own['price_sum_front_image'] = 0;
    for (var i = 1; i <= own['str_number']['front']['image']; i++)
    {
        own['price_sum_front_image'] = $('#front_image_content_str_'+i+'_price').html()*1 + own['price_sum_front_image'];
    }


    own['price_sum_back_text'] = 0;
    for (var i = 1; i <= own['str_number']['back']['text']; i++)
    {
        own['price_sum_back_text'] = $('#back_text_content_str_'+i+'_price').html()*1 + own['price_sum_back_text'];
    }
    own['price_sum_back_image'] = 0;
    for (var i = 1; i <= own['str_number']['back']['image']; i++)
    {
        own['price_sum_back_image'] = $('#back_image_content_str_'+i+'_price').html()*1 + own['price_sum_back_image'];
    }


    // если выделено 2 чекбокса и у каждой стороны заполнено хоть по одному полю - делаем наценку за обе стороны
    if ( (true == $('input[id=front_checkbox]:checkbox').attr('checked')) && (true == $('input[id=back_checkbox]:checkbox').attr('checked')) &&    ( ((0 != own['price_sum_front_text']) || (0 != own['price_sum_front_image'])) && ((0 != own['price_sum_back_text']) || (0 != own['price_sum_back_image'])) ) )
    {
        // делаем наценку за обе стороны
        $('#price_both_side').html(own['price_add']['front_and_back']);
        own['price_both_side'] = own['price_add']['front_and_back'];
    }
    else
    {
        $('#price_both_side').html(0);
        own['price_both_side'] = 0;
    }



    if ((0 != own['price_sum_front_text']) || (0 != own['price_sum_front_image']) || (0 != own['price_sum_back_text']) || (0 != own['price_sum_back_image']))
    {
        $('#button_add_cart').fadeIn('slow');
        $('#own_comment').fadeIn('slow');
    }
    else
    {
        $('#button_add_cart').fadeOut('slow');
        $('#own_comment').fadeOut('slow');
    }
        
    CalcPrice();
}

// проверка каптчи
function check_captha()
{
    var code = $('#_code').attr('value');

    $.ajax({
       type: "GET",
       url: request_url,
       data: 'ajax=true&action=check_captha&_code=' + code,
       dataType: "text",
       success: function(data){
            if ('false' == data)
            {
                refreshCode();
                $('#_code').attr('value', '');

                alert('Неверно введен код на картинке. Попробуйте еще раз');
                return false;
            }
            else
            {
                document.getElementById('addtocartform').submit();
                return true;
            }
       },
       error:function(XMLHttpRequest, textStatus, errorThrown){
           alert(XMLHttpRequest + '|' + textStatus +  '|' + errorThrown);
       }
     });


/*
    $.get(request_url, {ajax : 'true', action : 'check_captha', _code: code}, function(data){
        //false
        if ('false' == data)
        {
            refreshCode();
            $('#_code').attr('value', '');
            
            alert('Неверно введен код на картинке. Попробуйте еще раз');
            return false;
        }
        else
        {
            document.getElementById('addtocartform').submit();
            return true;
        }
    });*/
}

// клик на звездочку рейтинга
function rate(maket_idn, rate)
{
    if ('enabled' == rating)
    {
        $.get(request_url, {ajax : 'true', action : 'rate', rate: rate, maket_idn : maket_idn}, function(data){
            $('.star').rating('disable');

            $("#thankyou").fadeIn('slow');
        });
    }
}

 

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

// Редирект   на нужную модель с нужным цветом
function Model_show(model,color,url)
{
location.replace(url+'?model='+model+'&color='+color);
}

