
var isModernBrowser = document.createElement('canvas').getContext;

var slideTime = 4000, //main slider slide time
	productSlideTime = 3000; //product slider slide time
var animSpeed = 800;
var activeSlide = 0,
	play;

//******************* FONT REPLACEMENT
//********************************************************		
Cufon.replace('h2, h3, #top-links a', { hover: isModernBrowser });

//nav menu first-level links
Cufon.replace('#nav a', { hover: isModernBrowser });
Cufon.replace('#home-news h3', { hover: isModernBrowser, textShadow: '1px 1px #97661b)' });
//******************* FONT REPLACEMENT
//********************************************************


$(function () {



    //**********************************
    // FOOTER LOGOS
    //makeLogosScrollable();
    //playLogos();

    $('#logos a').hover(function () {
        if (isModernBrowser) {
            $(this).parent().siblings().stop().fadeTo(600, 0.4);
        }
        //clearInterval(playLogo);
        var tooltip = $(this).find('.tooltip');
        if (isModernBrowser) {
            tooltip.stop(true, true).slideDown(400);
        } else {
            tooltip.stop(true, true).slideDown(500);
        }
    }, function () {	  //hover out
        if (isModernBrowser) {
            $(this).parent().siblings().stop().fadeTo(500, 1);
        }
        //playLogos();
        var tooltip = $(this).find('.tooltip');
        tooltip.stop(true, true).slideUp(300);
    });
    //**********************************



    //**********************************
    // body - details
    if (!$('#slider').length) {
        $('body').addClass('details');
    }
    //**********************************



    //**********************************
    // header modal boxes
    $('a#login').click(function () {
        if ($(this).hasClass('active')) {
            HideLoginBox();
        } else {
            ShowLoginBox();
        }
        return false;
    });
    $('a#search').click(function () {
        if ($(this).hasClass('active')) {
            HideSearchBox();
        } else {
            ShowSearchBox();
        }
        return false;
    });

    //body e tıklanınca modalları kapat.	
    $('body, body *').click(function (e) {
        if ($(e.target).is('#top-links *')) { return; };
        HideLoginBox();
        HideSearchBox();
    });
    //**********************************


    //**********************************
    //WATERMARK 
    if ($('.watermark').length) {
        $(".watermark").each(function () {
            $(this).watermark($(this).attr('title'), { className: "watermark", useNative: false });
        });
    }
    //**********************************




    //*************************************
    //validation
    if ($('.validateForm').length) {
        $('.validateForm').each(function () {
            $(this).validate();
        });

    }
    //*************************************



    //**********************************
    // COLUMNS 
    $('.column').hover(function () {
        $(this).addClass('active').find('.desc').stop().animate({ height: $(this).find('.desc p').height() }, 600, 'easeInOutCirc');
    }, function () {
        $(this).removeClass('active').find('.desc').stop().animate({ height: 32 }, 600, 'easeInOutCirc');
    });
    //*************************************




    //**********************************
    // STYLED FORM ELEMENTS
    //styled selects -> selectbox plugin
    if ($('.category').length) {
        $('.category').selectbox();
    }
    //styled radio inputs -> uniform plugin
    if ($('.option-list').length) {
        $(".option-list input:radio").uniform();
    }
    //**********************************


    //**********************************
    // PRODUCT CONDITINAL VALIDATION	***update v1.5

    //enable first option
    $('.product').each(function () {
        $(this).find('.options .option:first .title').addClass('active');
        $(this).find('.product-images ul:first').show();
        $(this).find('.total-price').html($(this).find('.price-tag:first').addClass('current').html());
    });
    //show option list for active links
    $('.product a.title.active').live("click", function () {
        $(this).parent().find('.option-list').slideDown();
    });
    // radio input change -> activate next option	
    $('.option input').change(function () {
        var productNo = $(this).attr("productNo");

        $(this).parents('.option').nextAll('.option-block:first').find('.title').addClass('active');
        $(this).parents('.option').find('.title').html($(this).parents('label').find('span.text').html()); // ***update v1.3
        var productWrap = $(this).parents('.product');

        if ($(this).hasClass('color')) {	//change barcode value by color
            var index = $(this).parents('label').index();
            productWrap.find('.product-images ul').eq(index).show().siblings().hide();
            productWrap.find('.barkod-title').html(productWrap.find('.barkod').eq(index).html());
            productWrap.find('.price-tag').siblings().removeClass('current');
            productWrap.find('.price-tag').eq(index).addClass('current');
            var price = parseFloat(productWrap.find('.price-tag.current').html());
            var amountText = productWrap.find('.amount-current').html();
            var amount = amountText != null ? parseFloat(amountText) : 1;
            var totalPrice = price * amount;
            productWrap.find('.total-price').html(totalPrice.toFixed(2));
            productWrap.find('#btnAdd').find('#productHelperItem').remove();
            productWrap.find('#btnAdd').append("<input type='hidden' id='productHelperItem' productCode='" + productNo + "' amount='" + amount + "'/>");
        }
        if ($(this).hasClass('amount')) {	//calculate total price by amount
            $(this).parents('.option').find('.title').addClass('amount-current');
            var price = parseFloat(productWrap.find('.price-tag.current').html());
            var amount = parseFloat($(this).val());
            var totalPrice = price * amount;
            productWrap.find('.total-price').html(totalPrice.toFixed(2));
            var item = productWrap.find('#btnAdd').find('#productHelperItem')
            productWrap.find('#btnAdd').find('#productHelperItem').remove();
            productWrap.find('#btnAdd').append("<input type='hidden' id='productHelperItem' productCode='" + item.attr("productCode") + "' amount='" + amount + "'/>");
        }
    });
    //hide option list on mouse leave
    $('.option-list').mouseleave(function () {
        $(this).slideUp();
    });

    //change product cover image on hover
    $('.product-images a').mouseenter(function () {
        $(this).parents('.product').find('.product-cover a').attr('href', $(this).attr('rel')).find('img').attr('src', $(this).attr('href'));
        return false;
    });
    //do nothing on click
    $('.product-images a').click(function () {
        return false;
    });

    //Sepete ekleme olayı
    $('.active.add-to-basket').live("click", function () {
        var amount = $(this).find("#productHelperItem").attr("amount");
        var productID = $(this).find("#productHelperItem").attr("productCode");
        $.ajax({
            type: 'GET',
            url: 'http://www.kemerburgaz.com.tr/AddBasket.ashx',
            data: "ProductID=" + productID + "&Amount=" + amount,
            success: function (result) {
                if (result[1]) {
                    $.prompt("<img style=\"float:left;\ margin-right:10px;\" src=\" /_Assets/Images/SuccessMessageMid.png \" />Ürününüz sepete eklenmiştir. Alışverişe devam edebilir veya sepetinize giderek alışverişinizi tamamlayabilirsiniz.", {
                        callback: mycallbackform,
                        buttons: { "Alışverişe Devam Et": 'Tamam', "Sepete Git": 'Sepete Git' }
                    });


                } else {
                    $.prompt('Sepete Eklenemedi');
                }
            }
        });

        $('#aGoToBasket').load('http://www.kemerburgaz.com.tr/GetBasketProductCount.ashx');
        // $('.product-head .go-to-basket').slideDown();
    });

    function mycallbackform(v, m, f) {
        //        if (v != undefined)
        //            $.prompt(v + ' ' + f.alertName);
        if (v == "Sepete Git") {
            window.location = "/order/chekout/order.html"
        }

    }

    //update v1.5
    //**********************************


    //**********************************
    // PRODUCT TOOLTIP
    $('.product-cover').mouseover(function (e) {

        var tip = $(this).find('.tooltip');
        tip.css('top', e.pageY + 10);
        tip.css('left', e.pageX + 20);
        tip.stop().show();

    }).mousemove(function (e) {

        var tip = $(this).find('.tooltip');
        tip.css('top', e.pageY - $(this).offset().top + 10);
        tip.css('left', e.pageX - $(this).offset().left + 20);

    }).mouseout(function () {

        $(this).find('.tooltip').stop().hide();
    });
    //**********************************


    //**********************************
    // PRODUCTS PAGING
    $('.paging a').first().addClass('prev');
    $('.paging a').last().addClass('next');
    //**********************************


    //**********************************
    //TABLE STYLING
    $('table.styled tbody tr:even').addClass('alt');
    //**********************************


    //**********************************
    //lightbox
    if ($('.lightbox').length) { acitvateLightbox(); }
    //**********************************



    //**********************************
    // PRODUCT CATEGORY SELECT ACCORDION - update v1.3
    $('.category-select').click(function () {
        $('.category-wrap').fadeToggle(200);
    });

    $('.category-wrap li a').click(function () {
        var sub = $(this).parent().find('ul').first();
        if (sub.length) {
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                sub.stop(true, true).slideUp(400, 'easeInOutExpo');
            } else {
                //alert(sub.html());
                $(this).parent().siblings().find('.selected').removeClass('selected');
                $(this).parent().siblings().find('ul').stop(true, true).slideUp(400);
                $(this).addClass('selected');
                sub.stop(true, true).slideDown(400, 'easeInOutExpo');
            }

        }
    });
    //**********************************
    // PRODUCT CATEGORY SELECT ACCORDION - update v1.3



});               //end doc.load	




// window.onload
//*******************************
window.onload = function () {


    //MAIN SLIDER	
    //**********************************
    if ($('#slider').length) {
        $('#slider div').first().css("left", 0);
        $('#slider').orbit({
            animation: 'horizontal-push',                  // fade, horizontal-slide, vertical-slide, horizontal-push
            animationSpeed: 1000,                // how fast animtions are
            timer: true, 			 // true or false to have the timer
            advanceSpeed: 4000, 		 // if timer is enabled, time between transitions 
            pauseOnHover: false, 		 // if you hover pauses the slider
            startClockOnMouseOut: true, 	 // if clock should start on MouseOut
            startClockOnMouseOutAfter: 1000, 	 // how long after MouseOut should the timer start again
            directionalNav: true, 		 // manual advancing directional navs
            captions: true, 			 // do you want captions?
            captionAnimation: 'fade', 		 // fade, slideOpen, none
            captionAnimationSpeed: 800, 	 // if so how quickly should they animate in
            bullets: false, 		 // true or false to activate the bullet navigation
            bulletThumbs: false, 	 // thumbnails for the bullets
            bulletThumbLocation: '', 	 // location from this file where thumbs will be
            afterSlideChange: function () { }, 	 // empty function 
            easing: 'easeInOutExpo'
        });
    }
    //MAIN SLIDER	
    //**********************************



    //**********************************
    //news slider
    if ($('#home-news').length) {
        $('#home-news .scrollable').scrollable({ vertical: false, circular: false, speed: 800, easing: 'easeInOutExpo' }).autoscroll({ autoplay: false, interval: 5000 });
    }
    //**********************************


    //**********************************
    //logo animation
    if ($('#logo').length) { $('#logo').delay(400).animate({ height: 86 }, 1200, 'easeInOutExpo'); }
    //**********************************


    //**********************************
    //nav animation
    if ($('#nav').length) { $('#nav').slideDown(1200, 'easeInOutExpo'); }
    //**********************************


    //**********************************
    //top links animation
    if ($('#top-links').length) { $('#top-links a').each(function (i) { $(this).delay(i * 300 + 1200).slideDown(400); }); }
    //**********************************


    //**********************************
    //home news
    if ($('#home-news').length) { $('#home-news').delay(700).animate({ height: 161, top: 265 }, 1400, 'easeInOutExpo', function () { $(this).addClass('ready'); }); }
    //**********************************


    //**********************************
    //logos animation
    if ($('#logos').length) { $('#logos').delay(1000).slideDown(1600, 'easeInOutExpo'); }
    //**********************************

    //**********************************
    //footer animation
    if ($('#footer').length) { $('#footer').delay(100).fadeIn(1600, 'easeInOutExpo'); }
    //**********************************


    //**********************************
    //fade content
    if ($('.fade-area').length) {
        $('.fade-area').each(function (i) {
            $(this).delay(i * 200 + 200).fadeIn(400, 'easeInExpo');
        });
    }
    //**********************************


    //**********************************
    //slider loading
    if ($('#slider').length) { $('#slider').removeClass('loading'); }
    //**********************************


    //**********************************
    //TABLE STYLING
    $('table.styled tbody tr:even').addClass('alt');
    //**********************************
	
	$('.product-cover, .product-images .images li').each(function() {
        var img = $(this).find('img');
		var parentH = img.parent().height();
		var marginTop = (parentH - img.height())/2;
		img.css("margin-top",marginTop);
    });


}; //end window.onload	
//*******************************		




// MODAL BOXES FUNCTION
//**********************************
var modalSpeed = isModernBrowser ? 300 : null;

function ShowLoginBox() {
    HideSearchBox();
    $('a#login').addClass('active');
    $('#login-box').stop(true, true).show(modalSpeed);
}
function ShowSearchBox() {
    HideLoginBox();
    $('a#search').addClass('active');
    $('#search-box').stop(true, true).show(modalSpeed);
}
function HideLoginBox() {
    $('a#login').removeClass('active');
    $('#login-box').stop(true, true).hide(modalSpeed);
}
function HideSearchBox() {
    $('a#search').removeClass('active');
    $('#search-box').stop(true, true).hide(modalSpeed);
}
// MODAL BOXES FUNCTION
//**********************************




//LOGOS	FUNCTIONS
//**********************************
//make logos scrollable on mouse move
function makeLogosScrollable() {
    var div = $('div#logos'),
			ul = $('div#logos ul'),
			ulPadding = 20;

    var divWidth = div.width();
    //div.css({overflow: 'hidden'});
    var lastLi = ul.find('li:last-child');

    div.mousemove(function (e) {
        var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
        var left = (e.pageX - div.offset().left) * (ulWidth - divWidth) / divWidth;
        div.stop().animate({ scrollLeft: left }, 500, 'easeOutSine');
    });
}


// logos auto play	
var playLogo = null;
function playLogos() {

    var div = $('div#logos'),
			ul = $('div#logos ul'),
			ulPadding = 20;
    var divWidth = div.width();

    var totalWidth = 0;
    $('div#logos ul li').each(function () {
        totalWidth += $(this).width();
    });

    // ul ye dinamik width hesapla	
    ul.width(totalWidth);

    var direction = 1;
    var posX = div.scrollLeft();
    var speed = 1;

    playLogo = setInterval(function () {

        posX = div.scrollLeft();

        if (posX >= totalWidth - divWidth + ulPadding * 2) {
            direction = -1;
        }
        else if (posX == 0) {
            direction = 1;
        }

        if (direction == 1) {
            $('div#logos').stop().animate({ scrollLeft: "+=" + speed }, 10);
        } else {
            $('div#logos').stop().animate({ scrollLeft: "-=" + speed }, 10);
        }
    }, 40);
}
//LOGOS	FUNCTIONS
//**********************************


// LIGTHBOX
//*************************************
function acitvateLightbox() {

    var easingIn = isModernBrowser ? 'easeOutBack' : null;
    var easingOut = isModernBrowser ? 'easeInBack' : null;
    var transitionIn = isModernBrowser ? 'elastic' : 'none';
    var transitionOut = isModernBrowser ? 'elastic' : 'none';

    // Lightbox
    $("a.lightbox, .lightbox a").fancybox({
        'overlayColor': '#000',
        'overlayOpacity': '0.3',
        'padding': '3',
        'margin': '80',
        'width': 720,
        'height': 405,
        'autoDimensions': true,
        'modal': false,
        'showCloseButton': true,
        'opacity': true,
        'changeSpeed': 300,
        'transitionIn': transitionIn,
        'easingIn': easingIn,
        'easingOut': easingOut,
        'speedIn': 600,
        'speedOut': 500,
        'transitionOut': transitionOut,
        'hideOnOverlayClick': true,
        'centerOnScroll': true,
        'titlePosition': 'over',
        'titleFormat': formatTitle,
        'onComplete': function () { $("#fancybox-wrap").unbind('mousewheel.fb'); }
    });

}

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    var titleArray = title.split('-');
    return '<div class="fancyTitle">' + (title && title.length ? '' + titleArray[0] + '<span>' + titleArray[1] + '</span>' : '') + '</div>';
}
//*************************************
