$(function(){

	if ($.Storage!=undefined && $.Storage.get('autologin')!=undefined) {
		login(true);
	}

	//$('.button,button,.buttons a').button();

	/*
	$('.add-fav').live('click', function(){
		alert('add-cfav');
		return false;
	});
	$('.add-cart').live('click', function(){
		alert('add-cart');
		return false;
	});
*/

	$(".stickybox").stickySidebar({
				timer: 400
			, easing: "easeInOutBack"
		});
		
	// position the more menu
	$('#more-menu ul').css('margin-left',-1*($('#more-menu ul').width()-$('#more-menu').width()));

	// all marquee slowdown when mouseover
	$('marquee').each(function(){
	    			// keep original value
					$(this).attr('org',$(this).attr('scrollamount'));
				})
				.mouseenter(function(e){e.stopPropagation();$(this).attr('scrollamount', 0); })
				.mouseleave(function(e){ e.stopPropagation();$(this).attr('scrollamount',$(this).attr('org')); });

	// cart variety dropdown
	$('select.cart-variety').live('change', function(e) {
		var li = $(this).children().eq(this.selectedIndex);
		if ($(li).attr('data-photo')!='') $(this).parents('*[data-id]').find('img').attr('src', $(li).attr('data-photo'));
		$(this).parents('*[data-id]').find('.price').text($(li).attr('data-price'));
	});
	// add to cart buttons
	$('.add-fav, .add-cart').live('click', function(e){
		e.stopPropagation();

		if (parseInt($('#ajax-cart').css('bottom'))<0)
		{
			$('#ajax-cart').stop().animate({'bottom':0},'fast');
		}
		if (_t!=false) clearTimeout(_t);
		_t = setTimeout("$('#ajax-cart').stop().animate({'bottom':-216},'fast');",5000);

		// add new item to cart or fav
		if ($(this).hasClass('add-cart')) add_to_cart(this);
		else if ($(this).hasClass('add-fav')) add_to_fav(this);

		return false;
	});
	
	$('.clear-cart').live('click', function() {
	    if (confirm('Are you sure ?'))
	    {
			$.getJSON('cart.php',{a:'clear_cart'}, function(r){
				if(r.msg=='OK')
				{
					if (!$('#ajax-cart').get(0)) {
						document.location.reload();
						return false;
					}

					$('#ajax-cart .tab-cart').html(r.html);
					$('.cart-count').html(r.count);
					$('.cart-qty').html(r.qty);
					$('.cart-total').html(r.total);
				}
				else
		        {
					alert(r.msg==undefined?r:r.msg);
				}
			});
		}
		return false;
	});

	$('.del-fav, .del-cart').live('click', function(e){
		e.stopPropagation();

		// delete item from cart or fav
		if ($(this).hasClass('del-cart')) del_from_cart(this);
		else if ($(this).hasClass('del-fav')) del_from_fav(this);

		return false;
	});
/*
	// update IM status
	$.get('chat-helper.php?skype=yinsee', null, function(e){
		if(e==2 || e==7)
		{
			$('#chat-skype .offline').hide();
			$('#chat-skype .online').show();
		}
	});

	$.getJSON('chat-helper.php?msn=ab31af2d4c2e0e2@apps.messenger.live.com', null, function(e){
		if(e.status=='online')
		{
			$('#chat-msn .offline').hide();
			$('#chat-msn .online').show();
		}

	});

	// add text layer for placeholder backward-support
	if (!Modernizr.input.placeholder){
		$('input[placeholder]').each(function(){
			$('<span class="placeholder" style="position:absolute;margin:2px;color:grey;"></span>').insertBefore($(this)).html($(this).attr('placeholder')).css('display',($(this).val()=='' ? '' : 'none'));

			$(this).blur(function(){
				if ($(this).val()=='')
				{
					$(this).prev('.placeholder').css('display','');
				}
			});
			$(this).focus(function(){
				$(this).prev('.placeholder').css('display','none');
			});
		});
    }

*/
    // ajax cart tabs
	$('#ajax-cart .tab a').click(function(){
		$('#ajax-cart .tab-div').css('display', 'none');
		$('#ajax-cart .'+$(this).attr('rel')).css('display','');
		return false;
	});
	$('#ajax-cart').mouseenter(function(e){
		e.stopPropagation();
		if (parseInt($('#ajax-cart').css('bottom'))<0)
		{
			$('#ajax-cart').stop().animate({'bottom':0},'fast');
		}
	});

	$('#ajax-cart').mouseleave(function(e) {
		e.stopPropagation();
		if (parseInt($('#ajax-cart').css('bottom'))>=0)
		{
			$('#ajax-cart').stop().animate({'bottom':-216},'fast');
		}

	});

    // drag and drop products to cart
/*
	$('#content ul.products img').draggable({helper:'clone', start: function(){ $('#drop-cart').css('display','');}, stop: function(){ $('#drop-cart').css('display','none');}});
	$('#drop-cart').droppable({
	    //greedy: true,
	    accept: 'ul.products img',
		drop:function(e,ui){
			$(this).removeClass('over');
			ui.draggable.parents('*[data-id]').find('.add-cart').click();
		},
  		over: function(event, ui) { $(this).addClass('over'); },
  		out: function(event, ui) { $(this).removeClass('over'); }
	});
*/
	// checkout
	$('#shipping-location').live('change', function() {
		var val = this.value.split(/\|/);
		$('.shipping-fee').html(val[1]);
		$('.shipping-subtotal').html((parseFloat(val[1])+parseFloat($('#subtotal').val())).toFixed(2));
	});
	$('.shipping-courier').live('click', function() {
		$('.shipping-fee').html('-');
		$('.shipping-subtotal').html('-');
		$('#shipping-location').html('<option>-- Loading --</option>').load('cart.php',{ a:'get_shipping_locations', _id:$(this).attr('data-id') });
		$('.shipping-courier-id').val($(this).attr('data-id'));
	});


});


// cart drag drop 
var _t = false;
function del_from_cart(obj)
{
	if (!confirm('Are you sure?')) return false;
	var $target = $(obj).parent();
	var id = $(obj).parent().attr('data-uid');
	
	$target.fadeOut();
	$.getJSON('cart.php',{a:'del_from_cart',uid:id}, function(r){
		if (r.msg=='OK')
		{
			$target.remove();
			$('.cart-count').html(r.count);
	//		$('.cart-qty').html(r.qty);
			$('.cart-total').html(r.total);
			$('.cart-tax').html(r.tax);
		}
		else
		{
			$target.show();
			alert(r.msg==undefined?r:r.msg);
		}
	});
}

function add_to_cart(obj)
{
	$('#ajax-cart .tab-div').css('display', 'none');
	$('#ajax-cart .tab-cart').css('display','');

	var $p = $(obj).parents('*[data-id]');
	var id = $p.attr('data-id');
	/*if ($p.attr('data-variety')==1 && code=='')
	{
		alert('Select a model');
		$p.find('select').focus();
		return false;
	}*/
	
	var newitem = false;
	var img =  $p.find('img').attr('src');
	if (img!=undefined) newitem = $('<li></li>').appendTo('#ajax-cart .tab-cart ul').html('<img src="'+img+'">').css('opacity',0).animate({opacity:1},2000);
	var params = {};
	$.map($p.find('.add-cart-params').serializeArray(), function(n, i){
		params[n['name']] = n['value'];
	});
	
	$.getJSON('cart.php',{a:'add_to_cart',_id:id, params:params}, function(r){
		if(r.msg=='OK')
		{
			$('#ajax-cart .tab-cart').html(r.html);
			$('.cart-count').html(r.count);
			$('.cart-qty').html(r.qty);
			$('.cart-total').html(r.total);
		}
		else
        {
			if (newitem) $(newitem).remove();
			alert(r.msg==undefined?r:r.msg);
		}
	});
}

function del_from_fav(obj)
{
	var id = $(obj).parent().attr('data-id');
	$('li[data-id='+id+'],div[data-id='+id+']').removeClass('is-fav');

	$(obj).parent().fadeOut();
	$.getJSON('member.php',{a:'del_from_fav',_id:id}, function(r){
		if (r.msg=='OK')
		{
			$(obj).parent().remove();
			$('.fav-count').html(r.count);
		}
		else
		{
			$(obj).parent().show();
			alert(r.msg==undefined?r:r.msg);
		}
	});
}


function add_to_fav(obj)
{
	$('#ajax-cart .tab-div').css('display', 'none');
	$('#ajax-cart .tab-fav').css('display','');

	var $p = $(obj).parents('*[data-id]');
	var id = $p.attr('data-id');
	$('li[data-id='+id+'],div[data-id='+id+']').addClass('is-fav');

	var newitem = false;
	var img =  $p.find('img').attr('src');
	if (img!=undefined) newitem = $('<li></li>').appendTo('#ajax-cart .tab-fav ul').html('<img src="'+img+'">').css('opacity',0).animate({opacity:1},2000);

	$.getJSON('member.php',{a:'add_to_fav',_id:id}, function(r){
		if (r.msg=='OK')
		{
			$('.fav-count').html(r.count);
			if(newitem) 
				$(newitem).replaceWith(r.html);
			else
				$(r.html).appendTo('#ajax-cart .tab-fav ul');
		}
		else
		{
			if (newitem) $(newitem).remove();
			alert(r.msg);
		}
	});
}

// admin login
function login(is_auto)
{
	if (!is_auto && !check_required($('#login form').get(0),'.login-status'))
		return false;

	$('.login-status').html('Logging in...');

	var data = is_auto ? $.Storage.get('autologin') : $('#login form').serialize();

	$.post($('#login form').attr('action'), data, function(r){
		if (r=='OK')
		{
			if ($('#autologin').attr('checked'))
        	{
				// store autologin persistent data
				$.Storage.set('autologin',$('#login form').serialize());
			}
	        else if (!is_auto) // do not clear storage if we are auto login
	        {
	        	$.Storage.remove('autologin');
	        }

			$('.login-status').html('Login successful');
			document.location.reload();
		}
		else
			$('.login-status').html(r);
	});

	return false;
}

function logout()
{
	$.Storage.remove('autologin');
//	$('#wlogout').dialog('open');
//	return false;
//	return confirm('Are you sure?');
}


function check_required(f,div)
{
	var ret = true;
	$(f).find('input.required, input[required], select[required]').not(':checkbox')
		.each(function(){
			if ($(this).val()=='')
			{
				if (div!=undefined)
					$(div).html(($(this).attr('title')?$(this).attr('title'):$(this).attr('placeholder'))+' is required');
				else
					alert(($(this).attr('title')?$(this).attr('title'):$(this).attr('placeholder'))+' is required');
				$(this).focus();
				ret = false;
				return false;
			}
		});

	return ret;
}
