var currentCategory = 0;
var currentFeatures = new Array;
var restrictedAction = '';
var logged = 0;
var in_hover = 0;
var wishlist = 0;
var wishAdded = '';

function nap(m)
{
	var then = new Date(new Date().getTime() + m);
	while (new Date() < then) {}
}

//basket
function closeBasket() {
    $('div.inBasketBox').fadeOut('fast');
}

function openBasket() {
    $('div.inBasketBox').fadeIn('fast');
}

var minAction = false;
var maxAction = false;
var speed = 20;
var step = 5;
var img;
var stepCount = 0;
var ratio = 1;

function doMin()
{
	if (minAction==true) {
			if (stepCount>=10) {
				img.width(img.width()-step);
				img.height(img.height()-step*ratio);
			}
			stepCount++;
	}
	setTimeout("doMin()",speed);
}

function doMax()
{
	if (maxAction==true) {
		if (stepCount>=10) {
			img.width(img.width()+step);
			img.height(img.height()+step*ratio);
		}
		stepCount++;
	}
	setTimeout("doMax()",speed);
}

$(document).ready(function(){

	doMin();
	doMax();

	$(function() {
        $('#gallery a').lightBox();
    });

    //Zoom
(function($) {

    $.fn.zoomImg = function() {
	img =  this.find('#zoomBox #zoomBoxImg');
	var src = '';
	ratio = img.height()/img.width();

	if (this.find('#zoomList img').length > 0) {
	    src = this.find('#zoomList img').eq(0).attr('src').replace(/_thumb/,'_sub2');
	    img.attr('src',src);
	    img.draggable();
	}
		
	this.find('#zoomList img').click(function(){
		tmp = $(this).attr('class').split('a');
		width = tmp[0];
		height = tmp[1];
		ratio = height/width;
		if (tmp[0]>400) {
			width = 400;
			ratio2 = 400/tmp[0];
			height = ratio2*tmp[1];
			if (height>400) {
				ratio2 = 400/height;
				height = 400;
				width = 400*ratio2;
			}
		}
		else if (tmp[1]>400) {
			height = 400;
			ratio2 = 400/tmp[1];
			width = tmp[0]*ratio2;
			if (width>400) {
				ratio2 = 400/width;
				width = 400;
				height = 400*ratio2;
			}
		}
		img.css('top','0');
		img.css('left','0');
		img.width(width);img.height(height);
		src = $(this).attr('src').replace(/_thumb/,'_sub2');
	    img.attr('src',src);
	});

	this.find('#zoomMin').bind("mousedown", function(e){
		stepCount = 0;
		minAction = true;
    });
	this.find('#zoomMin').bind("mouseup", function(e){
		minAction = false;
		if (stepCount<10) {
			img.width(img.width()-40);
			img.height(img.height()-40*ratio);
		}
		stepCount = 0;
    });
	this.find('#zoomPlus').bind("mousedown", function(e){
		stepCount = 0;
		maxAction = true;
    });
	this.find('#zoomPlus').bind("mouseup", function(e){
		maxAction = false;
		if (stepCount<10) {
			img.width(img.width()+40);
			img.height(img.height()+40*ratio);
		}
		src2 = src.replace(/_sub2/,'');
		img.attr('src', src2);
		stepCount = 0;
    });

    };
})(jQuery);
    
    $('#zoom').zoomImg();

    $('#tabs').tabs();

    //topMenu
    $('div.topMenu  li').hover(
		function(){
			$(this).addClass('topMenuHover');
			$(this).find('div.subMenu').css('display','block');
		},
		function(){
			$(this).removeClass('topMenuHover');
			$(this).find('div.subMenu').css('display','none');
		}
    );

    //leftMenu
    $('ul.leftMenu a').click(function(){
	var subMenu = $(this).parent().find('ul');
	if (subMenu.css('display')=='none') {
	    $(this).addClass('active');
	    subMenu.fadeIn('fast');
	} else {
	    $(this).removeClass('active');
	    subMenu.fadeOut('fast');
	}
    });

    //FILTER
    
    $('div.filterBox li.resetFilter').click(function(){
		$('div.filterBox li.filter dd.selFilter').slideUp('fast',function(){$(this).remove()});
		currentFeatures = new Array;
		selectCategory(0);
    })
	
    $('div.filterBox li.filter').hover(
		function(event){
			if (!in_hover) {
				var t = setTimeout(function() {
					in_hover = 1;
				}, 100);
				$(this).stop().find('dd.bodyFilter').slideDown('fast');
			}
		},
		function(event){
			event.stopPropagation();
			event.preventDefault();
			if (in_hover) {
				in_hover = 0;
				$(this).stop().find('dd.bodyFilter').slideUp('fast');
			}
		}
    )

    $('div.filterBox li.filter dd.bodyFilter li').click(function(){
		var elemText = $(this).text();
		var parent = $(this).parents('li.filter');
		var addMarker = true;
		categoryId = $(this).attr('id').replace(/cat_/,'');
		if (parent.hasClass('category') && parent.find('dd.selFilter').length > 0) {
			parent.find('dd.selFilter').each(function(){
				if ($(this).text()==elemText) {
					addMarker = false;
				}
			});
			if (addMarker) {
				parent.find('dd.selFilter').remove();
				parent.find('dt.headFilter').after('<dd class="selFilter">'+elemText+'</dd>');
			}
		}
		else if (parent.find('dd.selFilter').length > 0) {
			parent.find('dd.selFilter').each(function(){
				if ($(this).text()==elemText) {
					addMarker = false;
				}
			});
			if (addMarker) {
				parent.find('dd.selFilter:last').after('<dd class="selFilter" id="cat2_'+categoryId+'" style="display:none;">'+elemText+'</dd>');
			}
			parent.find('dd.selFilter:last').slideDown('fast');
		}
		else {
			parent.find('dt.headFilter').after('<dd class="selFilter" id="cat2_'+categoryId+'" style="display:none;">'+elemText+'</dd>');
			parent.find('dd.selFilter:last').slideDown('fast');
		}

		// category click
		if (parent.hasClass('category')) {
			selectCategory(categoryId);
		}
		// feature click
		else {
			selectFeature(categoryId);
		}

		bindClick();
    })



    //Fade box
    var posImg = 0;
    $('div.fadeBoxImg div.action a').bind('click',function(e){
	var elem = $(this).parents('div.fadeBoxImg').find('div.fadeItem');
	var count = elem.length;
	if (($(this).attr('class')=='next')&&(posImg < count-1)) {
	    elem.eq(posImg).fadeOut('fast');
	    posImg++;
	    elem.eq(posImg).fadeIn('fast');
	}
	if (($(this).attr('class')=='prev')&&(posImg > 0)) {
	    elem.eq(posImg).fadeOut('fast');
	    posImg--;
	    elem.eq(posImg).fadeIn('fast');
	}
    })

    var posTxt = 0;
    $('div.fadeBoxTxt div.action a').bind('click',function(e){
	var elem = $(this).parents('div.fadeBoxTxt').find('div.fadeItem');
	var count = elem.length;
	if (($(this).attr('class')=='next')&&(posTxt < count-1)) {
	    elem.eq(posTxt).fadeOut('fast');
	    posTxt++;
	    elem.eq(posTxt).fadeIn('fast');
	}
	if (($(this).attr('class')=='prev')&&(posTxt > 0)) {
	    elem.eq(posTxt).fadeOut('fast');
	    posTxt--;
	    elem.eq(posTxt).fadeIn('fast');
	}
    })

	//SHOPPING CART
	$('.sizeselect').bind('change',function(e){
		option_id = $(this).attr('name').replace(/id_/,'');
		value = $(this).attr('value');
		$('#cart_quantity').ajaxSubmit();
	});
	$('.remove_product').bind('click',function(e){
		tmp = $(this).attr('rel').split('_');
		$('#delete_'+tmp[2]).attr('value', tmp[1]);
		$('#cart_quantity').submit();
	});


});

function product_submit(str)
{
	if ($('#size').attr('value')=='') {
		alert(str);
		return false;
	}
	wishlist = 0;
	$('#add_to_cart').submit();
}

function addToWishlist(str)
{
	if ($('#size').attr('value')=='') {
		alert(str);
		return false;
	}
	wishAdded = $('#wishlistBtn').attr('rel');
	wishlist = 1;
	prevAction = $('#add_to_cart').attr('action');
	$('#add_to_cart').attr('action', $('#wishlistBtn').attr('rev'));
	$('#add_to_cart').submit();
}

//FILTER
function bindClick() {
	$('div.filterBox li.filter dd.selFilter').bind('click',function(){
	    $(this).slideUp('fast',function(){
			if($(this).parents('li.filter').hasClass('category')) {
				selectCategory(0);
			}
			else {
				deleteFeature($(this).attr('id').replace(/cat2_/,''));
			}
			$(this).remove();
		})
	});
}

function selectCategory(categoryId)
{
	if ($('#blockChange').attr('value')==undefined) {
		
		breadStr = $('div.breadcrumbs').html();
		breadStr = breadStr.split(baseUrl).join('');
		breadStr = breadStr.replace(' />',' >');
		breadStr = breadStr.replace('<IMG','<img');
		breadStr = breadStr.replace('<img alt="" src="img/breadcrumbs-marker.png" >','<img src="img/breadcrumbs-marker.png" alt="" >');
		breadStr = breadStr.replace('<img alt="" src="img/breadcrumbs-marker.png">','<img src="img/breadcrumbs-marker.png" alt="" >');
		if (categoryId == 0) {
			tmp = breadStr.split('<img src="img/breadcrumbs-marker.png" alt="" >');
			$('div.breadcrumbs').html(tmp[0]);
			$('div.pageTitle').html($('#defaultTitle').attr('value'));
		}
		else {
			tmp = breadStr.split('<img src="img/breadcrumbs-marker.png" alt="" >');
			str = tmp[0] + '<img src="img/breadcrumbs-marker.png" alt="" />';
			str = str + '<a class="headerNavigation" href="'+baseUrl+'category/'+categoryId+'">'+$('#cat_'+categoryId).html()+'</a>';
			$('div.breadcrumbs').html(str);
			$('div.pageTitle').html($('#cat_'+categoryId).html());
		}
	}
	currentCategory = categoryId;
	$('#currentPage').attr('value',1);
	$('#compareFrm input[name=ids]').attr('value', '');
	updateSearchResults();
}

function selectFeature(featureId)
{
	currentFeatures[currentFeatures.length] = featureId;
	$('#currentPage').attr('value',1);
	$('#compareFrm input[name=ids]').attr('value', '');
	updateSearchResults();
}

function deleteFeature(featureId)
{
	tmp = new Array;
	for (i=0; i<currentFeatures.length; i++) {
		if (currentFeatures[i]!=featureId) {
			tmp[tmp.length] = currentFeatures[i];
		}
	}
	currentFeatures = tmp;
	$('#currentPage').attr('value',1);
	$('#compareFrm input[name=ids]').attr('value', '');
	updateSearchResults();
}

function updateSearchResults()
{
	$('#results').fadeTo('normal', 0.33);
	$('#loader').show();
	$.ajax({
		type: 'POST',
		url: baseUrl+'ajax_products.php',
		data: ({categoryId: currentCategory, featureId: currentFeatures.join(','), page: $('#currentPage').attr('value')}),
		success: function(response){
			//update results
			$('#results').html(response);
			$('#results').fadeTo('fast', 1);
			$('#loader').hide();
			assignCompare();
		}
	});
}

function setPage(page)
{
	$('#currentPage').attr('value', page);
	updateSearchResults();
}

$(document).ready(function(){
	bindClick();
	if ($('#cPath').attr('value')!=undefined) {
		tmp = $('#cPath').attr('value').split('_');
		currentCategory = tmp[0];
		if (tmp.length>1) {
			currentFeatures[currentFeatures.length] = tmp[1];
		}
	}

	if ($('#add_to_cart') != undefined) {
		$('#add_to_cart').submit(function() {
			var options = {
				beforeSubmit: function(){
					$('#addLoader').show();
				},
				success: function(response){
					$('#addLoader').hide();
					if (wishlist) {
						$('#add_to_cart').attr('action', prevAction);
						showAlert(wishAdded);
						wishlist = 0;
					}
					else {
						$('#basket').html(response);
						openBasket();
					}
				}
			};
			$(this).ajaxSubmit(options);
			return false;
		});
	}

	$('.showLogin').bind('mousedown',function(event){
		if (!logged) {
			event.stopPropagation();
			event.preventDefault();
			if ($(this).attr('href') != 'javascript:void(0)' && $(this).attr('href') != 'javascript:void(0);') {
				restrictedAction = 'window.location = "'+$(this).attr('href')+'"';
			}
			else {
				if (!jQuery.browser.msie) {
					restrictedAction = $(this).attr('onclick')+'; onclick();';
				}
				else {
					restrictedAction = $(this).attr('onclick')+'; anonymous();';
				}
			}
			showDiv($('#loginDiv'));
		}
	});
	$('#loginFrm').submit(function() {
		var options = {
			beforeSubmit: function(){
				$('#loginLoader').show();
			},
			success: function(response){
				$('#loginLoader').hide();
				if (response != 'ok') {
					$('#loginError').html(response);
				}
				else {
					logged = 1;
					hideDiv($('#loginDiv'));
					eval(restrictedAction);
				}
			}
		};
		$(this).ajaxSubmit(options);
		return false;
	});

	/*PRODUCT_INFO page*/
	if ($('#reviewFrm') != undefined) {
		$('#reviewFrm').submit(function() {
			var options = {
				beforeSubmit: function(){
					$('#reviewLoader').show();
				},
				success: function(response){
					$('#reviewLoader').hide();
					if (response != 'ok') {
						$('#reviewError').html(response);
					}
					else {
						hideDiv($('#reviewDiv'));
						alert($('#reviewThankx').html());
					}
				}
			};
			$(this).ajaxSubmit(options);
			return false;
		});
	}
	assignCompare();
});

//COMPARE FEATURE
function assignCompare()
{
	$('.compare').bind('click',function(event){
		if ($('#compareFrm input[name=ids]').attr('value') == '') {
			alert($(this).attr('rel'));
		}
		else {
			$('#loader').show();
			$.ajax({
				type: 'GET',
				url: baseUrl+'ajax_compare.php',
				data: ({ ids: $('#compareFrm input[name=ids]').attr('value') }),
				success: function(response){
					//update results
					$('#loader').hide();
					$('#compareResults').html(response);
					showDiv($('#compareDiv'));
				}
			});
		}
	});

	$('.compare_checkbox').bind('click',function(event){
		ids = $('#compareFrm input[name=ids]').attr('value');
		if ($(this).attr('checked')) {
			if (ids == '') {
				ids = $(this).attr('value');
			}
			else {
				ids = ids+','+$(this).attr('value');
			}
			$('#compareFrm input[name=ids]').attr('value', ids);
		}
		else {
			tmp = ids.split(',');
			ids = '';
			for (i=0;i<tmp.length;i++) {
				if (tmp[i] != $(this).attr('value')) {
					if (ids == '') {
						ids = tmp[i];
					}
					else {
						ids = ids+','+tmp[i];
					}
				}
			}
			$('#compareFrm input[name=ids]').attr('value', ids);
		}
	});

	elements_array = $('#compareFrmOriginal').attr('elements');
	if (elements_array != undefined) {
	for(i=0;i<elements_array.length;i++){
		if(elements_array[i].type=="checkbox" && $('#compareFrm input[name=ids]').attr('value').indexOf(elements_array[i].value) != -1){
			elements_array[i].checked = true;
		}
	}
}
}

//POPUP

function showAlert(str, elem)
{
	if (elem != undefined) {
		str = $('#'+elem).html();
	}
	$('#msgText').html(str);
	if (wishlist == 1) {
		$('#viewWishlist').removeClass('hidden');
	}
	else {
		$('#viewWishlist').addClass('hidden');
	}
	showDiv($('#msgDiv'));
}

function showDiv(elem)
{
	$('#bgshadow').show();
	var heightElem = elem.height();
	var widthElem = elem.width();
	elem.css({
		'display':'block',
		'position':'absolute',
		'z-index':'1000',
		'top': (heightElem > $(window).height()) ? ( $(window).scrollTop() + 10 + 'px') : (($(window).height() - heightElem)/2 + $(window).scrollTop() + 'px'),
		'left': (widthElem > $(window).width()) ? ( $(window).scrollLeft() + 10 + 'px') : ((($(window).width() - widthElem)/2 )+ 'px')
	});
	elem.insertAfter($('#bgshadow'));
}

function hideDiv(elem)
{
	elem.hide();
	$('#bgshadow').hide();
}

/* RETAILERS */
function getstates(country){
	$('#stores').html('');
	$('#cities').html('');
	$('#states').html('');
	$('#storeLoader').show();
	$.ajax({
		type: 'GET',
		url: baseUrl+'ajax_getprovinces.php?country='+country,
		success: function(response){
			//update results
			$('#storeLoader').hide();
			$('#states').html(response);
		}
	});
}

function getcities(state){
	$('#stores').html('');
	$('#storeLoader').show();
	$('#cities').html('');
	$.ajax({
		type: 'GET',
		url: baseUrl+'ajax_getcities.php?state='+escape(state),
		success: function(response){
			//update results
			$('#storeLoader').hide();
			$('#cities').html(response);
		}
	});
}

function getstores(city, state){
	$('#stores').html('');
	$('#storeLoader').show();
	$.ajax({
		type: 'GET',
		url: baseUrl+'ajax_getstores.php?state='+escape(state)+'&city='+escape(city),
		success: function(response){
			//update results
			$('#storeLoader').hide();
			$('#stores').html(response);
		}
	});
}
