var zoomImagesURI   = '/simages/zoom/'; // Location of the zoom and shadow images
var compareItemIds = new Array();
var comparedCat;

$(document).ready(function() {
    
    var compareBoxItemCount = parseInt($("#compareBoxItemCount").text());

    // compare function
    $('.ccomp').live("click", function(event) {
        
        var itemId = parseInt($(this).attr('value'));

        if($(this).attr('checked')) { 
            
            if(compareItemIds.length === 10) {
                alert('En fazla 10 ürünü karşılaştırabilirsiniz...');
                $(this).attr('checked', false);
            } else if(compareItemIds.length > 0) {
                if(comparedCat !== $(this).attr('ccompcat')) {
                    $('.ccomp').attr('checked', false); 
                    $(this).attr('checked', true);                    
                    comparedCat = $(this).attr('ccompcat');
                    compareItemIds = [itemId];
                } else if(!compareItemIds.contains(itemId)){ 
                    compareItemIds[compareItemIds.length] = itemId; 
                }
            } else {
                compareItemIds[compareItemIds.length] = itemId;
                comparedCat = $(this).attr('ccompcat');
            }            
            
        } else if(compareItemIds.contains(itemId)){ 
            compareItemIds.splice(compareItemIds.indexOf(itemId),1); 
        }

        populateCompareCookies();
    });

    $('.ccomp2').live("click", function(event) {

        var itemId = parseInt($(this).attr('value'));

        if($(this).attr('checked')) {

            if(compareItemIds.length === 10) {
                alert('En fazla 10 ürünü karşılaştırabilirsiniz...');
                $(this).attr('checked', false);
            } else if(compareItemIds.length > 0) {
                if(comparedCat !== $(this).attr('ccompcat')) {
                    $('.ccomp2').attr('checked', false);
                    $(this).attr('checked', true);
                    comparedCat = $(this).attr('ccompcat');
                    compareItemIds = [itemId];
                } else if(!compareItemIds.contains(itemId)){
                    compareItemIds[compareItemIds.length] = itemId;
                }
            } else {
                compareItemIds[compareItemIds.length] = itemId;
                comparedCat = $(this).attr('ccompcat');
            }

        } else if(compareItemIds.contains(itemId)){
            compareItemIds.splice(compareItemIds.indexOf(itemId),1);
        }

        populateCompareCookies();
    });

    var brandSelected;

    readCompareCookies();
    populateCheckbox();

    $('a.merchantInfo').cluetip({
       cluetipClass:   'jtip',
       local:          false,
       positionBy:     'bottomTop',
       topOffset:      20,
       leftOffset:     0,
       arrows:         true,
       width:          '450px',
       height:         'auto',
       showTitle:      false,
       activation:     'click',
       sticky:         true,
       closePosition:  'bottom',
       closeText:      'Kapat',
       fx: {open: 'fadeIn'},
       ajaxSettings: {dataType: 'html'}
    });

    $('a.lspec').cluetip({
        cluetipClass:   'jtip2',
        local:          false,
        attribute:      'href',
        topOffset:      20,
        leftOffset:     0,
        arrows:         true,
        width:          '200px',
        height:         'auto',
        showTitle:      false,
        activation:     'click',
        sticky:         true,
        closePosition:  'bottom',
        closeText:      'Kapat',
        fx: {open: 'fadeIn'},
        ajaxSettings: {dataType: 'html'}
    });

    $('.sponsor_mag_popup').cluetip({
        cluetipClass: 'sponsorpopup',
        local: true,
        hideLocal: true,
        showTitle: false,
        width: '474px',
        height: 'auto',
        closeText: '',
        positionBy: 'mouse',
        clickThrough: true,
        attribute: 'sponsor-popup',
        fx: {open: 'fadeIn'}
    });



    $('a.title').cluetip({splitTitle: '|'});

    $('.prev, .next, .lpaging').click(function(event) {
       populateCompareCookies();
    });

    $('.lcomp').click( function(event) {

       var compareUrl='';
       var count = compareItemIds.length;
       if(count > 10){
            alert('En fazla 10 ürünü karşılaştırabilirsiniz...');
       } else if(count < 2) {
            alert("En az iki ürün seçmeniz gerekiyor.");
       } else {
            compareUrl += "_" + compareItemIds.join("_");
            populateCompareCookies();
            window.location = 'C' + comparedCat + compareUrl;
       }
       return false;
    });


    // root categories
    $('a.RC, a.LC,a.mlink').click(function(event) {
       eraseCookie('compareItemIds');
       eraseCookie('comparedCat');
    });

    var compareReferer = readCookie("compareReferer");

    if(compareReferer == null){
        createCookie("compareReferer", window.location);
    }

    $(".eklecikar").each(function(){

        var itemId = parseInt($(this).attr("itemId"));

        try {
            var link = compareBoxItemIds == null
                        ? '<a href="#" itemId="' + itemId + '" class="laddtocmp" onmouseout="UnTip()"><img src="/simages/yeni_tasarim/buton_sepete_ekle.gif" width="185" height="25" alt="" /></a>'
                        : parseInt($.inArray(itemId, compareBoxItemIds)) < 0
                            ? '<a href="#" itemId="' + itemId + '" class="laddtocmp" onmouseout="UnTip()" ><img src="/simages/yeni_tasarim/buton_sepete_ekle.gif" width="185" height="25" alt="" /></a>'
                            : '<a href="#" itemId="' + itemId + '" class="ldelcmp"  onmouseover="UnTip()" ><img src="/simages/yeni_tasarim/buton_sepetten_cikar.gif" width="185" height="25" alt="" /></a>';
                            
            $(this).html(link);

        }catch(e){ }

    });

    $('.laddtocmp').live("click", function() {

       var link = $(this);

       $.ajax({
            type: "POST",
            url: "/MemberServlet/saveToMyList",
            data: "itemId=" + $(this).attr("itemId"),
            success: function(msg){
                 compareBoxItemCount = parseInt($("#compareBoxItemCount").text());
                 $("#compareBoxItemCount").text(++compareBoxItemCount + "");
                 $(link).removeClass("laddtocmp").addClass("ldelcmp");
                 $(link).html('<img src="/simages/yeni_tasarim/buton_sepetten_cikar.gif" >');
                 Tip('<img src=/simages/sepete_eklenmistir.png>');
            }
       });
       return false;
    });

    $('.ldelcmp').live("click", function() {
       var link = $(this);
       $.ajax({
            type: "POST",
            url: "/MemberServlet/dropFromMyList",
            data: "itemId=" + $(this).attr("itemId"),
            success: function(msg){
                 compareBoxItemCount = parseInt($("#compareBoxItemCount").text());
                 $("#compareBoxItemCount").text(--compareBoxItemCount);
                 $(link).removeClass("ldelcmp").addClass("laddtocmp");
                 $(link).attr("onclick",UnTip());
                 $(link).html('<img src="/simages/yeni_tasarim/buton_sepete_ekle.gif" >');
            }
       });

       return false;
    });

    $('.bdelcmp').live("click", function() {
        var link = $(this);
        var itemId = $(this).attr("itemId");
        var categoryId = $(this).attr("categoryId");

        $.ajax({
            type: "POST",
            url: "/MemberServlet/dropFromMyList",
            data: "itemId=" + itemId,
            success: function(msg){
                compareBoxItemCount = parseInt($("#compareBoxItemCount").text());
                
                $("#compareBoxItemCount").text(--compareBoxItemCount);
                $("#itemCountDiv").text("(" + compareBoxItemCount + ")");
                var inCompareItems = $.inArray(parseInt(categoryId), categoryIdList);
                $("div[itemId=" + itemId + "]").fadeOut("slow", function(){
                    $(this).remove();
                });
                compareItemIds.splice(compareItemIds.indexOf(itemId),1);

                if(parseInt(inCompareItems) < parseInt(0)){
                    $("div[categoryDiv=" + categoryId + "]").fadeOut("slow", function(){
                        $(this).remove();
                    });
                } else {
                    categoryIdList[parseInt(inCompareItems)] = -1;
                    var last = $.inArray(parseInt(categoryId), categoryIdList);
                    if(parseInt(last)< parseInt(0)){
                        $("div[categoryDiv=" + categoryId + "]").fadeOut("slow", function(){
                            $(this).remove();
                        });
                    }
                }

            }
        });

        return false;
    });


    //$('.lredirect').live("click",function(ev, ob){
    $('.lredirect').live("click", function(ev, ob){
        //openInNewWindow($(this).attr("href"));
        $.ajax({type: "GET", async: false, url: "/ClickServlet?sid=" + $(this).attr('sid')});
        pageTracker._trackPageview('/outgoing/' + $(this).attr("murl") + "/" + $(this).attr("href").replace(/http:\/\//, "") );
        return true;
    });


    $('.lredirectFlower').click(function(){
        pageTracker._trackPageview('/outgoing/' + $(this).attr("murl"));
            
    });

    $('.limgpopup300').click(function(){
       $('#bigImgPop').fadeIn("fasr");
       return false;
    });


    /** Vitrin urunlere sari cerceve */
    $('.list-showcased-item-div').wrapAll('<div style="border: 1px solid #f5c21b"></div>');

//    $('.dev-kampanyalar-anasayfa-link:in-viewport').live(function() {
//        console.log($(this).attr("href"));
//    });

    /* Humana kategori sponsorlugu */
    if(catName4SEO == 'bebek'){

        $(document.body).css({
            'background': 'url(/simages/body_bg_bebek.png) top center repeat-x #ffffff fixed'
        }) ;

        var linkWidth = ($(document).width() - $("#main").width() - 40) / 2

        var leftLink =
            $('<a class="lredirect" href="http://www.humanaturkiye.com" target="_blank" ></a>')
                .css({
                    'position': 'absolute' ,
                    'top': '160px' ,
                    'left': '0px',
                    'width': linkWidth ,
                    'height': '1240px',
                    'overflow': 'hidden'
                    });

        var rightLink =
            $('<a class="lredirect" href="http://www.humanaturkiye.com" target="_blank"></a>')
                .css({
                    'position': 'absolute' ,
                    'width': linkWidth,
                    'top': '160px' ,
                    'left': $(document).width() - linkWidth - 20,
                    'height': '1240px',
                    'overflow': 'hidden'
                    });

        $(document.body).append(leftLink).append(rightLink);
        
    } else if(catName4SEO == 'bilgisayar-yazilimlar'){

        $(document.body).css({
            'background': 'url(/simages/body_bg_bilgisayar.png) top center repeat-x #ffffff fixed'
        }) ;

        var linkWidth = ($(document).width() - $("#main").width() - 40) / 2

        var leftLink =
            $('<a class="lredirect" href="http://www.teknosa.com/msib21/tsaforms/redir.aspx?idURL=1450&requestFrom=689" target="_blank" ></a>')
                .css({
                    'position': 'absolute' ,
                    'top': '160px' ,
                    'left': '0px',
                    'width': linkWidth ,
                    'height': '1240px',
                    'overflow': 'hidden'
                    });

        var rightLink =
            $('<a class="lredirect" href="http://www.teknosa.com/msib21/tsaforms/redir.aspx?idURL=1451&requestFrom=689" target="_blank"></a>')
                .css({
                    'position': 'absolute' ,
                    'width': linkWidth,
                    'top': '160px' ,
                    'left': $(document).width() - linkWidth - 20,
                    'height': '1240px',
                    'overflow': 'hidden'
                    });

        $(document.body).append(leftLink).append(rightLink);
    }

  

});


function populateCheckbox(){
   $('#products :input:not(:button, :submit)').each(function(index){
        if( !compareItemIds.contains(parseInt($(this).attr('value'))) ){
             $(this).attr('checked', false);
        } else {
             $(this).attr('checked', true);
        }
   });
}
  
function populateCompareCookies(){
    eraseCookie('compareItemIds');
    eraseCookie('comparedCat');
    createCookie('compareItemIds', compareItemIds);
    createCookie('comparedCat', comparedCat);
}

   
function readCompareCookies(){
    var cookie = readCookie('compareItemIds');
    if(cookie != null ) {
        compareItemIds = [];
        strProducts = cookie.split(',');
        $.each(strProducts, function(v) {
            compareItemIds.push(parseInt(strProducts[v]));
        });
    }
    comparedCat = readCookie('comparedCat');
}
    
function buildCompareItems(){
    var url = window.location.href;
    var index = url.lastIndexOf('/')+2;
    var queryStr = url.substring(index);
    var items = queryStr.split('_');
    comparedCat = items[0];
    $.each(items, function(v) {
        compareItemIds.push(parseInt(items[v]));
    });
}


function openInNewWindow(url) {
    var newWindow = window.open(url, '_blank');
    newWindow.focus();
}
    

