/**
 * Created by .
 * User: beholder
 * Date: 4/26/11
 * Time: 5:39 PM
 */

$.fn.delay = function(options) {
    var timer;
    var delayImpl = function(eventObj) {
        if (timer != null) {
            clearTimeout(timer);
        }
        var newFn = function() {
            options.fn(eventObj);
        };
        timer = setTimeout(newFn, options.delay);
    }

    return this.each(function() {
        var obj = $(this);
        obj.bind(options.event, function(eventObj) {
             delayImpl(eventObj);
        });
    });
};

function goToPage(page){
    document.location.href = $.param.querystring(document.location.href, 'page=' + page);
}

// =============== Product sorting =====================
function product_sorting_init(){

    $('select[name="sort"]').change(function(){
        var param_value = $(this).val();
        document.location.href = $.param.querystring(document.location.href, 'sort=' + param_value);
    });

    $('.show a').click(function(){
        var param_value = $(this).attr('data');
        document.location.href = $.param.querystring(document.location.href, 'count=' + param_value);
        return false;
    });
}
// =============== Product sorting =====================

// =============== Left Filter =====================
function lf_check_submit($button){
    var $filter = $button.parent();
    if($(':checkbox:checked', $filter).length > 0){
        $button.show();
    }
    else {
        $button.hide();
    }
}

function lf_init(){
    $('.lf_submit').each(function(){
        var $button = $(this);
        lf_check_submit($button);
    });

    $('.filter :checkbox').click(function(){
        var $filter = $(this).parent().parent();
        lf_check_submit($('.lf_submit', $filter))
    });

    $('.lf_submit').click(function(){
        var url = $(this).attr('href');
        var filter_str = document.location.pathname.replace(url, '');
        var bits = filter_str.split(';');
        if (!bits[0]){
            bits = [];
        }
        var $filter = $(this).parent();
        $(':checkbox:checked', $filter).each(function(){
            bits.push($(this).val());
        });
        filter_str = bits.join(';');
        document.location.href = url + filter_str;
        return false;
    });
}
// =============== Left Filter =====================

function userLoginOverlay(){
    $('#userLogin a').overlay({
		onBeforeLoad: function() {
			// grab wrapper element inside content
			var wrap = this.getOverlay().find(".contentWrap");
			// load the page specified in the trigger
            $.getJSON(this.getTrigger().attr("href"), function(data){
                wrap.html(data.html);
            });
		}
	});

    $('#userLoginOverlay .checkout-button').live('click', function(){
        var form = $(this).parent();
        form.ajaxSubmit({
            "type" : "post",
            "dataType": "json",
            "success" : function(data) {
                var $userLoginLink = $('#userLogin a');
                $('#userLoginOverlay .contentWrap').html(data.html);
                if (data.hide){
                    $userLoginLink.data('overlay').close();
                    $('#userLogin').load($userLoginLink.attr('data'));
                }
            }
        });
    });
}

// Search ##################################################################
function SearchInit(){
    $("#search-input").live("blur", function(e) {
        window.setTimeout(function() {
            $("#livesearch-result").hide();
        }, 200);
    });

    $("#search-input").delay({
        delay: 400,
        event: "keyup",
        fn: function(e) {
            if (e.keyCode == 27) {
                //$("#livesearch-result").hide();
            }
            else {
                var q = $("#search-input").attr("value");
                var url = $("#search-input").attr("data");
                $.get(url, {"q" : q}, function(data) {
                    if (data.state == "success") {
                        $("#livesearch-result").html(data.products);
                        $("#livesearch-result").slideDown("fast");
                    }
                    else {
                        $("#livesearch-result").html();
                        $("#livesearch-result").hide();
                    }
                })
            }
        }
    });
}

// file input
function fileInput() {
	var file = $('div.elemBox.file input[type="file"]');
	var inputText = file.parent().next().children('input[type="text"]');

	file.change(function () {
		var fileVal = $(this).val();
		inputText.attr('value', fileVal);
	});
}

function secondClass() {
	$('.dropMenu td > ul > li:nth-child(2n)').addClass('rightLi');

	$('.recBrands > li:nth-child(3n)').addClass('right');

	$('.catalogList.lastLevel > li:nth-child(4n)').next('li').addClass('clAll');
	if ($.browser.msie && $.browser.version <= 7) {
		$('.catalogList.lastLevel > li:nth-child(4n)').after('<li class="cl"></li>');
	}

	if ( $('.mainMenu > li').hasClass('brands') ) {
		$('.mainMenu > li.brands .dropMenu td > ul > li').removeClass('rightLi');
		$('.dropMenu td > ul > li:nth-child(7n)').next('li').addClass('rightBrandLi');
		if ($.browser.msie && $.browser.version <= 7) {
			$('.dropMenu td > ul > li:nth-child(7n)').after('<li class="cl"></li>');
		}
	}
}

// add hover class
function hover() {
	$('.mainMenu > li, .catalog > li, .allBrands td').hover(
		function () {
			$(this).addClass('hover');
		},
		function () {
			$(this).removeClass('hover');
		}
	);
}

function checkForm() {
	$('input[type="radio"]:checked').next('label.check').addClass('act');
	$('input[type="checkbox"]:checked').next('label.check').addClass('act');

	$('input[type="radio"], input[type="checkbox"]').live('change', function () {
		var $type = $(this).attr('type');
		if ( $type == 'radio' ) {
			var $name = $(this).attr('name');

			$('input[name="' + $name + '"]').next('label.check').removeClass('act');
			$(this).next('label.check').addClass('act');
		}
		else {
			$(this).next('label.check').toggleClass('act');
		}
	});
}

function tabSwitch() {
	$('dl.tabs dt').click(function () {
		$(this).siblings().removeClass('select').end().next('dd').andSelf().addClass('select');
	});
}

function brandsList() {
	$('.brandsList .brandTitle').click(function () {
		$(this).parent('li').siblings('li').removeClass('select')
		$(this).parent('li').addClass('select');
	});
}

// card
function cardHide() {
	$('.oneCard #paypal').click(function () {
		$('.cardSelect').css('display', 'none');
	});

	$('.oneCard #visa, .oneCard #mastercard').click(function () {
		$('.cardSelect').css('display', 'block');
	});
}

// ie6
function ieRedirect() {
	if ( $.browser.msie && $.browser.version <= 6 ) {
		$(window.location).attr('href', '/media/ie6upgrade/ie6Update.html');
	}
}

$(function(){
    product_sorting_init();
    lf_init();
    userLoginOverlay();
    SearchInit();
    checkForm();
});
