$(document).ready(function() {
	$("a.zoom").imgbox();
	$('#sidebar .cat ul li').hover(function() {
	  $(this).addClass('menu-hover');
	  $(this).prev().addClass('menu-hover-bottom');	
	}, function() {
	  $(this).removeClass('menu-hover');
	  $(this).prev().removeClass('menu-hover-bottom');
	}).bind('mouseenter',function(){
		$(this).find('div:first').show();
	}).bind('mouseleave',function(){
		$(this).find('div:first').hide();
	});	
	
	$('a.card').click(function() {
		var c = $(this).parent().children("input[type=text]").val();
		var lCard = $(this);
		var prod = $(this).parents('.prod-options');
		//var prod = $(this).parent().parent();
		var colorID = $(prod).find('.color-id').val();
		if(colorID==undefined)
			colorID=0;
		var sizeID = $(prod).find('.size-id').val();
		if(sizeID==undefined)
			sizeID=0;
		
		var url = "web2.php?ajax//basket/add/" + $(this).attr("href") + c + '/' + colorID+'/'+sizeID+'/';
		$.get(url, {}, function(json){
			if(json.added)
			{
				lCard.msgColorTip({color:'topshop', timeout:2000, dest: 'parent'});
				$("#bQuantity").html("("+json.quantity+")");
			}
		},"json");
		
		return false; 
	}).show();	
	
	
		
	$('a.wishlisttocart').click(function() {
		var lCard = $(this);
		var url = "web2.php?ajax//basket/add/" + $(this).attr("href");
		$.get(url, {}, function(json){
			if(json.added)
			{
				lCard.msgColorTip({color:'wishlist', timeout:2000, dest: 'parent'});
				$("#wCount").html("("+json.quantity+")");
			}
		},"json");
		
		return false; 
	}).show();	
		
	$('a.wishlist').click(function() {
		var lCard = $(this);
		var prod = $(this).parents('.prod-options');
		var colorID = $(prod).find('.color-id').val();
		if(colorID==undefined)
			colorID=0;
		var sizeID = $(prod).find('.size-id').val();
		if(sizeID==undefined)
			sizeID=0;
		
		var url = "web2.php?ajax//wishlist/add/" + $(this).attr("href") + colorID+'/'+sizeID+'/';
		$.get(url, {}, function(json){
			if(json.added)
			{
				lCard.msgColorTip({color:'topshop', timeout:2000, dest: 'parent'});
				$("#wCount").html("("+json.count+")");
			}
		},"json");
	
		return false; 
	}).show();
	
	$("#bonus").keyup(function(){
		var balance = parseFloat($(".balance em").text());
		var bonus = $(this).val();
		var totalsum = $("#totalsum").val();
		
		if(isNaN(bonus) || bonus<0)
			bonus=0;
		if(bonus>balance)
			bonus = balance;
			
		$(this).val(bonus);
		$("#bonus_src").val(bonus);
		var diff = totalsum-bonus;
		diff = Math.roundup(diff, 2);
		$(".totalsum em").html(diff);
		});
		
	
	$("#points").keyup(function(){
		var allPoints = parseFloat($(".points em").text());
		var points = $(this).val();//points_to_money
		var totalsum = $("#totalsum").val();
		
		if(isNaN(points) || points<0)
			points=0;
		if(points>allPoints)
			points = allPoints;
			
		$(this).val(points);
		$("#points_src").val(points);
		
		var points_money = (points>0)?Math.roundf(points/points_to_money, 2):0;
		//console.log(points_money);
		$(".points_money").html(points_money);
		
		var diff = totalsum-points_money;
		diff = Math.roundup(diff, 2);
		$(".totalsum em").html(diff);
		});

	$(".quantity").keypress(function (e)  
	{
	  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
	  {
		//$("#errmsg").html("Digits Only").show().fadeOut("slow");
		$(this).next().html(jslang.digits_only).show().fadeOut("slow"); 
	    return false;
      }	
	});
		
	$("#logout").click(function(){
		$("#formlogout").submit();
		return false;
	});
	$("a.login_link").click(function(){	
		
		if ($.browser.msie && $.browser.version.substring(0,1) < 7)
			$("#login_pane").css('left', $(this).position().left-85);
		else
			$("#login_pane").css('left', $(this).position().left);
		//$("#login_pane").toggle(400);
		var status = ($("#login_pane").is(':visible'))?'hide':'show';
		$("#login_pane").animate({ opacity: status }, "slow");
		return false;
		});
	$("a.popuplink").click(function(){
		var prefix = this.id.split('_')[0];
		var pane = $("#"+prefix+"_pane");
		var pos = getCenter(pane);
		pLeft = pos.pLeft;
		pTop = pos.pTop;
		
		pane.css({top: pTop, left: pLeft});
		//pane.toggle(400);
		var status = (pane.is(':visible'))?'hide':'show';	
		pane.animate({ opacity: status }, "slow");
		return false;
	});
		
	$(".pane .close").click(function(){
		$(this).parents(".pane").animate({ opacity: 'hide' }, "slow");
	});	
	$("#tema-toggle").click(function(){
		var body = $("#tema-panel");
		if(body.is(":hidden"))
	      body.slideDown();
	    else
	      body.slideUp();
    	return false;
		//$("#tema-panel").slideUp("slow");
	});	
	
	
	
	function dailycarousel_initCallback(carousel)
	{
	    // Disable autoscrolling if the user clicks the prev or next button.
	    /*
	    carousel.buttonNext.bind('click', function() {
	        carousel.startAuto(0);
	    });

	    carousel.buttonPrev.bind('click', function() {
	        carousel.startAuto(0);
	    });
	    */

	    // Pause autoscrolling if the user moves with the cursor over the clip.
	    carousel.clip.hover(function() {
	        carousel.stopAuto();
	    }, function() {
	        carousel.startAuto();
	    });
	    
	    //setupCallback
	};
	
	function dailycarousel_setupCallback(carousel)
	{
		$('#daily-slider li').show();
	}

	$('#daily-slider').jcarousel(
	{	scroll:1,
		auto:4,
		wrap: 'circular',
		buttonNextHTML:"<button></button>",
		buttonPrevHTML:"<button></button>",
		initCallback: dailycarousel_initCallback
		});
	//$('#daily-slider li').show();
	
	imagePreview();
	multiImg();
	
	addLis();
	
	forSizeAndColors();
	
	forExpandOrder();
	
	checkBoxes();
	
});


Math.roundf = function(val, precision)
{
	var p = this.pow(10, precision);
	return this.round(val * p) / p;
}

Math.rounddown = function(val, precision)
{
	var p = this.pow(10, precision);
	return this.floor(val * p) / p;
}

Math.roundup = function(val, precision)
{
	var p = this.pow(10, precision);
	return this.ceil(val * p) / p;
}

function checkBoxes(chkname, do_check)
{
	var elts = document.getElementsByName(chkname+'[]');
    var len  = elts.length;

    if (len)
    {
        for (var i = 0; i < len; i++)
        {
            elts[i].checked = do_check;
        }
    }
    else
    {
        elts.checked = do_check;
    }
    return true;
}

function checkBoxes()
{ 
    // add multiple select / deselect functionality
    $(".item-selectall").click(function () {
          $('.item-select').attr('checked', this.checked);
    });
 
    // if all checkbox are selected, check the selectall checkbox and viceversa
    $(".item-select").click(function(){
        if($(".item-select").length == $(".item-select:checked").length) {
            $(".item-selectall").attr("checked", "checked");
        } else {
            $(".item-selectall").removeAttr("checked");
        }
    });
}

function addLis()
{
	$("#invite_btn").click(function(){
		var stop = false;
		var email = $('#invite_email');	
		var name = $('#invite_name');
			
		if (email.val()=='') 
		{
	        email.addClass("sel");
	        stop=true;
	    }
	    else
	    	email.removeClass("sel");
    
	    if (name.val()=='') 
	    {
	        name.addClass("sel");
	        stop=true;
	    }
	    else
	    	name.removeClass("sel");
	
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) 
		{
	        email.addClass("sel");
	        stop=true;
	    }
	    else
	    	email.removeClass("sel");
		if(stop)
			return false;
		
		$.post("web2invite.php",
		{ emailTo: email.val(), emailFrom: name.val() },
		function(data){
			
			if(data=='1')
			{
				$("#msgInvite").html(jslang.invite_success);
				name.val("");
				email.val("");
			}
			else
				$("#msgInvite").html(data);
			/*	
			$("#sendInvite").slideUp("normal", function() {
				if(data=='1')
					$("#sendInvite").before('<span id="msgInvite">'+jslang.invite_success+'</span>');
				else
					$("#sendInvite").before('<span id="msgInvite">'+data+'</span>');
			});*/
		}
		);
	
	});
}

function getCenter(pane)
{
	var wnd = $(window);
	var doc = $(document);
	var pTop = doc.scrollTop();
	var pLeft = doc.scrollLeft();
	var	minTop = pTop;
	
	//alert(wnd.height() );

	var h = 0//wnd.height();
	h = document.getElementsByTagName('html')[0].clientHeight
	
	pLeft += (wnd.width() - pane.outerWidth()) / 2;
	pTop += (h - pane.outerHeight()) / 2;
	//document.getElementsByTagName('html')[0].clientHeight;

	pTop = Math.max(pTop, minTop);

	var pos = {pLeft : pLeft, pTop : pTop};
	return pos;
}


var _ = function(id)
{
	return document.getElementById(id);
}
function textSwitch(obj, e, title)
{
	if(e=='focus')
	{
		if(obj.value == title)
			obj.value = '';	
	}
	else
	{
		if(obj.value == '')
			obj.value = title;
	}
}	
var srch_def = jslang.srch_def;
var login_def = jslang.login_def;

function srch()
{
	var key = _('key').value;
	if(key!='' && key!=srch_def)
		_('search').submit();
}

function onLogin(id)
{
	var key = _(id).value;
	if(key!='' && key!=login_def)
		return true;
	else
		return false;
}

function subm(frm, id, val)
{
	var key = _(id).value;
	if(key!='' && key!=val)
		_(frm).submit();
}
function CheckEmpty(f, theName)
{ 
	if (f.value == "") 
	{ 
		alert(theName + " "); 
		f.focus(); 
		f.select(); 
		return false; 
	} 
	else 
	{ 
		return true; 
	}
}

function multiImg()
{
	var $loader	= $('.holder');//$('#st_loading');
	//$loader.show();
	$('.images li, .annimages li').hover(
		function(){
			$(this).toggleClass('hover');
		},
		function(){
			$(this).toggleClass('hover');
		});
	$('.images a, .annimages a').click(function(){
		
			var $this = $(this);
			var href = $this.attr('href');
			var hArr = href.split('::');
			var src = hArr[0];
			var w = hArr[1];
			var h = hArr[2];
			var osrc = hArr[3];
			$('ul.images li, ul.annimages li').removeClass('sel');
			$this.parent().addClass('sel');
			$loader.show();
			$('<img/>').load(function(){
				var $this = $(this);
				var $img = $('.imgholder img');
				var $a = $('.imgholder a');	
				
				var $s = $this.attr('src');
				$a.attr('href',src);
				$a.imgbox();
				//$a.addClass('zoom');
				
				var $str = '<img src="'+$s+'"';
				if(w>0 && !osrc)	$str += ' width="'+w+'"';
				if(h>0 && !osrc)	$str += ' height="'+h+'"';
				$str += '/>';
				
				//$img.removeAttr('width').removeAttr('height');
				//alert($str);
				//$img.attr('src',$s);
				//$img.html($str);
				
				$img.replaceWith($str);
				$loader.hide();
			}).attr('src',src);	
			
			return false;
		});
}


this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.srcc = this.title;
		if(this.srcc!="")
		{
		this.t = '';
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		var img = new Image();
		img.src = this.srcc;
		$("body").append("<p id='preview'><img src='"+ img.src +"' alt='' />"+ c +"</p>");
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");					
		}	
    },
	function(){		
		this.title = this.srcc;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){	
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

function forSizeAndColors()
{
	$(".sizes a").hover(function(){
		var parent = $(this).parents('.size-cont');
		parent.find(".size-selected em").html($(this).text());
	}, function(){
		var parent = $(this).parents('.size-cont');
		var def = parent.find(".size-default").val();
		if(def!='')
			parent.find(".size-selected em").html(def);
	}).click(function(){
		var size = $(this).text();
		var sizeID = $(this).attr("href").substring(1);
		var parent = $(this).parents('.size-cont');
		parent.find(".sizes a").removeClass("active");
		$(this).addClass("active");
		parent.find(".size-default").val(size);
		parent.find(".size-id").val(sizeID);
		parent.find(".size-selected em").html(size);
		return false;
	});
	
	$(".colors a").click(function(){
		var colorID = $(this).attr("href").substring(1);
		var parent = $(this).parents('.color-cont');
		parent.find(".colors a").removeClass("sel");
		$(this).addClass("sel");
		parent.find(".color-id").val(colorID);
		return false;
	});
}

function forExpandOrder()
{
	$("div .change").hover(function(){
		$(this).css('border-color', '#F7AF42');
	}, function(){
		$(this).css('border-color', 'transparent');
	}).click(function(){
		var div = $(this).parent().parent().next().find(".shipmentItems");
		if(div.is(":hidden"))
		{
			div.slideDown();
			$(this).addClass('expand');
	  	}
	    else
	    {
			div.slideUp();
			$(this).removeClass('expand');
	  	}
    	return false;
	});
}

/*********************UNICODE FUNCTIONS************************/
var unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~";
var reserved = "!*'();:@&=+$,/?%#[]";
var allowed = unreserved + reserved;
var hexchars = "0123456789ABCDEFabcdef";


function gethex(decimal) {
  return "%" + hexchars.charAt(decimal >> 4) + hexchars.charAt(decimal & 0xF);
  }

function encode(for_decode,charset) {

  var decoded = for_decode;
  var encoded = "";


  if (charset == "ascii") {

    var notascii = "";

    for (var i = 0; i < decoded.length; i++ ) {
      var ch = decoded.charAt(i);
      if (unreserved.indexOf(ch) != -1) {
        encoded = encoded + ch;
      } else {
        var charcode = decoded.charCodeAt(i);
        if (charcode < 128) {
          encoded = encoded + gethex(charcode);
        } else {
          encoded = encoded + ch;
          notascii = notascii + ch + " ";
        }
      }
    }
	return encoded;
    if (notascii != "") alert("Warning: Non-ASCII characters in decoded text!\n\nThus, these characters have not been encoded:\n" + notascii);
  }


  if (charset == "utf8") {
    for (var i = 0; i < decoded.length; i++ ) {
      var ch = decoded.charAt(i);
      if (unreserved.indexOf(ch) != -1) {
        encoded = encoded + ch;
      } else {

        var charcode = decoded.charCodeAt(i);

        if (charcode < 128) {
          encoded = encoded + gethex(charcode);
        }

        if (charcode > 127 && charcode < 2048) {
          encoded = encoded + gethex((charcode >> 6) | 0xC0);
          encoded = encoded + gethex((charcode & 0x3F) | 0x80);
        }

        if (charcode > 2047 && charcode < 65536) {
          encoded = encoded + gethex((charcode >> 12) | 0xE0);
          encoded = encoded + gethex(((charcode >> 6) & 0x3F) | 0x80);
          encoded = encoded + gethex((charcode & 0x3F) | 0x80);
        }

        if (charcode > 65535) {
          encoded = encoded + gethex((charcode >> 18) | 0xF0);
          encoded = encoded + gethex(((charcode >> 12) & 0x3F) | 0x80);
          encoded = encoded + gethex(((charcode >> 6) & 0x3F) | 0x80);
          encoded = encoded + gethex((charcode & 0x3F) | 0x80);
        }

      }

    }  // end of for ...
    return encoded;
  }
}
