var showmodal = false;
$(document).ready(function(){
	$('#semitrans').click(function(e){
		e.preventDefault();
		closeModal();
	});
	var loc = window.location+"";
	if(loc.indexOf('cat.php', loc.lastIndexOf('/'))!=-1
		|| loc.indexOf('product.php', loc.lastIndexOf('/'))!=-1
		|| loc.indexOf('index.php', loc.lastIndexOf('/'))!=-1)
		window.scroll(0,510);
});

function closeModal(){
	$('#loginbox').css('display','none');
	$('#semitrans').css('display','none');
}
function modalWindow(contentDiv,semi){
	if(!showmodal) return;
	$('#'+contentDiv).css('display','block');
	$('#'+semi).css('display','block');
	var height = ($(window).height()>$(document).height())?$(window).height():$(document).height();
	var width = ($(window).width()>$(document).width())?$(window).width():$(document).width();
	$('#'+semi).css('height',height);
	$('#'+semi).css('width',width);	
	$('#'+contentDiv).css('top',50);
	$('#'+contentDiv).css('left',(width/2-224));

}

$(window).resize(function() {
	modalWindow('loginbox','semitrans');
});	

$(function () {
	// display login box if user wants to login
	$('#displayloginbox').click(function(e){
		e.preventDefault();
		showmodal=true;
		modalWindow('loginbox','semitrans');
	});
	// login button activate
	$('#login_button').click(function(){
		var url='login.php';
		var data = getFormData('loginform');
		$.ajax({ url: url,async: false, cache:false, data:data, success: function(data){
				if(data.indexOf('ERROR:')>-1)
					alert(data);
				else if(data.indexOf('SUCCESS:')>-1) {
					window.location = 'disclaimer.php';
				} //else alert(data);
			}
		});
	});
	
	
	/*
	// logout button
	$('#logout').click(function(){
		var url='login.php';
		var data = getFormData('logoutform');
		$.ajax({ url: url,async: false, cache:false, data:'logout=true', success: function(data){
				if(data.indexOf('ERROR:')>-1)
					alert(data);
				else {
					window.location = window.location;
				}
			}
		});
	});
	*/

	
    $('ul>li:has(.is_sub)','#footer')
	.hover(function () {
		var is_sub=$(this).find('.is_sub');
		var left=$(this).position().left;
		//alert(left);
        is_sub.filter(':not(:animated)').css({left:left}).slideDown('fast');
		$(this).hover(
				  function () {},
				  function () {
					  is_sub.slideUp('fast');
				  });
    }).hover(
     	function(){$(this).addClass('hover');},
		function(){$(this).removeClass('hover');}
	);
});

isIE=function(v){
	return typeof v=='undefined' && $.browser.msie?true:($.browser.version.substring(0,1) == v? true: false);
}
	
imagePreloader=function (imageArray) {
	var dir=imagePreloader.dir||'';
	//alert(imageArray.length);
	$(window).load(function () {
		$.each(imageArray, function (i, m) {
			$(new Image()).load(function(){
							//alert(m);			 
						    }).attr('src', dir+m);
		});

	})
}

loadProductImages=function(){
		var productimages=$('img[src^=productimages]').map(function(){ 
											return $(this).attr('src').replace( /(.*)(\/)(.*)(\.)(jpg|png|gif)$/i,'$3$4$5' ); }).get();
		imagePreloader.dir='productimages/square/';
		imagePreloader(productimages);
		imagePreloader.dir='productimages/selected/';
		imagePreloader(productimages);
		imagePreloader.dir='productimages/slide/';
		imagePreloader(productimages);
}

loadDATA=function(ref,success){
	$.ajax({
		   type: $(ref).attr('method')||"GET", 
		   url: $(ref).attr('href')||$(ref).attr('action'), 
		   data: $(ref).attr('href')||$(ref).serialize(),
		   success: success
	});
}

function slider(sliders){
		//if(typeof sliders=='undefined') alert('hi');
		$.each(sliders,function(i,s){
				//alert(s.img);
				var parent ='#slider-'+s.id;
				var full=parent+' #FPO_full';
				var thumb=parent+' #FPO_thumb';
				if(s.img=='' || s.img==null || typeof s.img=='undefined') { 
					s.img='<div class=msg>No Images found</div>';
				}
				$(full+','+thumb).empty();
				$(s.img).appendTo(full); 
				cycle(full,thumb,'scrollHorz');
		});

}

function cycle(full,thumb,fx){
    $(full).cycle({
		fx: fx, 
        //speed: 3000,
        timeout: 3000,
        pager: thumb,
        //pagerEvent: 'mouseover',
		//pause:'#topnav a[rel=sexylightbox]',
		pauseOnPagerHover: true,
		//before:function(){$('a#SLB-CloseButton').length?$(full).cycle('pause'):$(full).cycle('resume');},
		//after: function(){$('a#SLB-CloseButton').length?$(full).cycle('pause'):cycle(full,thumb);},
		pagerAnchorBuilder: function(idx, slide) { 
        return '<a href="#"><img src="' + slide.src.replace('/slide/','/square/') + '" /></a>'; 
    	}
    }).hover(
		function(){$(this).cycle('pause')
		},
		function(){$(this).cycle('resume')
		}
	).find('img').each(function(i){
		(new Image()).src=this.src.replace('/slide/','/square/');
	})
	
}
function cycle_ready(full,thumb,fx){
  var off=$(full).offset();
  var loading=$('<div id=loading/>').css({position:'absolute',zIndex:1000,left:off.left,top:off.top}).prependTo('body').hide().text('loading...');
  var first_slide = $('img:first',full);
  if(is_image_loaded(first_slide.get(0))){
	  loading.hide('slow').remove();
	  cycle(full,thumb,fx);
  } else {
	  first_slide.load(function(e){
		  loading.hide('slow').remove();
		  $(full).show();
		  cycle(full,thumb,fx);
	  })
	  loading.show();
	  $(full).hide();
  }
}
var is_image_loaded = function(img) {
    return (!img.complete || (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) )?false:true;// IE || others
	return true;
}

title2text=function(ref,res){
	if(!$(ref).length) return false;
	var klass='activeProduct';
	$(ref).each(function(i,o){
				 var t=$('.'+klass,o).attr('title'); $(res,o).text(t);
				 $('a',o).hover(
				 		function(){var t=$(this).attr('title'); $(res,o).text(t);;},
				 		function(){var t=$('.'+klass,o).attr('title')||''; $(res,o).text(t);}
				 ).click(function(){
					    clicked=this;
					 	$('a',o).removeClass(klass);
					 	$(this).addClass(klass);
						add2bagURL('.'+klass,clicked);
						return false;
					 });//.eq(0).mouseover().click();
			   });
}

add2bagURL=function(res,clicked){
	var parent=$(clicked).parents('.main_frame').get(0);
	var btn='a#addItem';
	if(!$(btn).length) return false;
	var prop=[];
	var code=[];
	var $product=$(res,'#shop_it').eq(0);
	var sppc,extendURL,addURL,productURL='';
	//alert($(res).length);
	$(res,parent).each(function(i,o){
			var p=$(o).attr('href');
			//alert(p);
			prop[i]=p.split('?')[1];
			/*
			if(($(o).attr('href')||$(o).val()).match(/\d+$/)){
				code[i]=($(o).attr('href')||$(o).val()).match(/\d+$/);
			
			} else
				alert($(o).attr('href'));
			//alert(($(o).attr('href')||$(o).val()).match(/\d+$/));
			*/
	});
	
	//sppc=code.join('-');
	sppc="";
	extendURL=prop.join('&');
	code = extendURL.split('&');
	for(k=0; k<code.length; k++){
		var values = code[k].split('=');
		if(values[0]=='product_id'||values[0]=='style_code'||values[0]=='color_code'||values[0]=='size_code'){
			sppc+=values[1]+"-";
			
		}
	}
	
	
	addURL=$(btn).attr('href').replace(/(pssc=)(.*)$/,'$1'+sppc+'&'+extendURL);
	//productURL=$product.attr('href').split('?')[0];
	//$product.attr('href',productURL+'?'+extendURL);
	$(btn).attr('href',addURL);
	if(clicked==$(res,'#'+parent.id+' #item_color').get(0)){ 
	    var url='cart_ajax_slider.php';
		$.ajax({
			   url:url,
			   data:extendURL,
			   type:"GET",
			   success:function(data){
				  var sliders=eval('('+data+')');
				  slider(sliders);
				}
			   });
	}
	//$product.click();
	
}

function focus_blur(sel){
	$(sel).each(function(i,o){
		$(o).focus(function(){if(this.value==this.defaultValue) this.value='';})
			.blur(function(){this.value=($.trim(this.value)=='')?this.defaultValue:$.trim(this.value);});
	 });
}

accordian=function(parent){
    var aPARENT=parent;
	var aHEAD='.aHEAD';
	var aBODY='.aBODY';
	$(aBODY,aPARENT).hide().eq(0).show();
	$(aHEAD+':not(.disable)',aPARENT).live('click',function(){
		if($(this).next().is(':visible')) return false;
		$(aBODY,aPARENT).stop().slideUp('slow');
		$(this).next().stop().slideDown('slow');
	});
}

String.prototype.isValidEmail=function(){
	re= new RegExp("^([a-z0-9])+([._])?([a-z0-9_.])+@([a-z0-9])+\.([a-z0-9]){2,}$","ig");
	return emailCheck(this);
//	return this.match(re)==null?false:true;
}

String.prototype.isValidNumber=function(){
	return this.match(/^\d+$/)==null?false:true;
}
String.prototype.isValidPhone=function(){
	return this.match(/^[\d\s\-\(\)\,]+$/)==null?false:true;
	//return this.match(/^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/)==null?false:true;
}

String.prototype.isValidAlfaNumaric=function(){
	return this.match(/^[\w ]+$/)==null?false:true;
}

isValidForm=function($form){
	var form = $form.get(0);
	var $field=$form.find(':input:text:not(:disabled,.optional),select[name=province]');
	var error=[];
	var elem=[];
	var focusClass='sexyFocus';
	var index=0;
	$field.each(function(i,o){
			$(o).val($.trim($(o).val()));
			if( $(o).val()=='' || $(o).val()==o.defaultValue 
							   || ($(o).is('[name*=email]')&&!$(o).val().isValidEmail()) 
							   || ($(o).is('.numeric')&&!$(o).val().isValidNumber())
							   || ($(o).is('.phone')&&!$(o).val().isValidPhone())
							   || ($(o).is('.alphanumeric')&&!$(o).val().isValidAlfaNumaric())
							   || (o==form.confirm_email && form.email.value!=form.confirm_email.value) 
							   ){
				error[index]=true;
				elem[index]=o;
				index+=1;
				//$(o).removeClass(focusClass);
			}
			else{
				//error[i]=false;
				//$(o).removeClass(focusClass);
			}
	}).removeClass(focusClass);
	
	if(elem.length){
		$(elem).addClass(focusClass).eq(0).focus();
		//alert(elem[0].name);
		return false;
		}
	else {
		return true;
		//alert('no error');
	}
}

function isSameAddress(chk,same_as_form){
	var this_form=chk.form;
	var same_as_form=same_as_form||'form#ship_info';
	var $disElem=$(this_form).find(':input:not(:submit,:image,[name='+chk.name+'])').removeClass('sexyFocus');
	if(chk.checked){
		$(chk).val(1);
		$disElem.attr('disabled','disabled');
		$(same_as_form).find(':input').each(function(i,o){
												  $(':input',this_form).eq(i+1).val($(o).val());
												  });
	}
	else{
		$(chk).val(0);
		$disElem.removeAttr('disabled');
		$(same_as_form).find(':input').each(function(i,o){
												  $(':input',this_form).eq(i+1).val(o.defaultValue);
												  });
	}
	return chk.checked?true:false;
}


var dateMaker={
  selector:{day:'day',
  			month:'month',
			year:'year'
			},
  today:new Date(),
  months:['January','February','March','April','May','June','July','August','September','October','November','December'],
  makeDay:function(){
	var sel=document.getElementById(this.selector.day);
	var today=this.today;
	for (var i=1; i<=31; i++)
	sel.options[i]=new Option(i, i);
	sel.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true); 
  },
  makeMonth:function(){
	  var sel=document.getElementById(this.selector.month);
	  var today=this.today;
	  for (var m=0; m<12; m++)
	  sel.options[m]=new Option(this.months[m], m+1);
	  sel.options[today.getMonth()]=new Option(this.months[today.getMonth()],today.getMonth()+1, true, true);
  },
  
  makeYear:function(sel){
	  var sel=document.getElementById(this.selector.year);
	  var today=this.today;
	  var thisyear=today.getFullYear()
	  for (var y=0; y<20; y++){
	  sel.options[y]=new Option(thisyear, thisyear);
	  thisyear+=1;
	  }
	  sel.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true);
  },
  
  init:function(){
				this.makeDay();
				this.makeMonth();
				this.makeYear();
			  }
			  
}

//leapYear---(year%4==0)&&(year%100!=0||year%400==0)

function daysInMonth(month,year) {
	var dd = new Date(year, month, 0);
	return dd.getDate();
}
function setDayDrop(dyear, dmonth, dday) {
	var year = dyear.val();
	var month = dmonth.val();
	var day = dday.val();
	var days =daysInMonth(month,year);
	dday=dday.get(0);
	dday.options.length = 0;
	for (var i = 1; i <= days; i++)
		dday.options[dday.options.length] = new Option(i,i);
	day=day>days?1:day;
	dday.options[day]=new Option(day, day, true, true); 

}

function setDay(form) {
	var year = $('select[id*=year]',form);
	var month = $('select[id*=month]',form);
	var day = $('select[id*=day]',form);
	setDayDrop(year,month,day);
	var date=year.val()+'-'+month.val()+'-'+day.val();
	var $expiry_date=$('input[name=expiry_date]',form);
  	$expiry_date.val(date);
	//alert($expiry_date.val());
}


$.fn.tip=function(msg,callback){
		var self=$(this);
		if($(this).is(':input')){ 
		var over='focus';
		var out='blur';
		}
		else{
		var over='mouseover';
		var out='mouseout';
		}
		self.bind(over,function(){ 			   
		var $this=$(this);
		var off=$this.offset();
		var type=($this.is(':input:text'))?'type':'select';
		var title=$this.attr('title')
		var msg=title||'Please '+type+' your '+$this.attr('name').replace(/(^(shipping|billing)|_)/ig,' ');
		$this.attr({title:'',alt:title});
		var $tip=$('<div class=tip>'
				   +'<div class=xsnazzy>'
				   +'<div class=xtop><div class=xb1></div><div class=xb2></div><div class=xb3></div><div class=xb4></div></div>'
      			   +'<div class=xboxcontent>'
				   +msg
				   +'</div>'
      			   +'<div class=xbottom>'
				   +'<div class=xb4></div><div class=xb3></div><div class=xb2></div><div class=xb1></div>'
				   +'</div>'
				   +'<div class=tip-arrow></div>'
				   +'</div>').prependTo(document.body)
		.css({ 
			 left:off.left, 
			 top:off.top, 
			 position: 'absolute', 
			 marginLeft: ($this.width()-$('.tip').width())/2
			 }).hide().fadeIn('fast');	
		}).bind(out,function(){
				$this=$(this);
				$this.attr({title:$this.attr('alt')});
				$('.tip').fadeOut(function(){ $(this).remove();});
		});
	return self;
}


$.fn.modal=function(seed){
	var seed=seed||'';
	var self=$(this);
	var MWindow='#modal-window';
	var MOverlay='#modal-overlay';
	self.live('click',function(e) {
		e.preventDefault();
		//alert('hi');
		//var page=$(this).attr('href')
		$('.country',MWindow).each(function(i,o){
											$(o).attr('href','your_bag.php?country='+$(o).attr('title')+seed);
											});
		//var id = $(this).attr('href');
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
		$(MOverlay).css({'width':maskWidth,'height':maskHeight,'opacity':0}).fadeTo("slow",0.8);
		var winH = $(window).height();
		var winW = $(window).width();
		var mTop1=($(document).scrollTop() + ($(window).height() - $(MWindow).outerHeight()) / 2 );
		var mTop2=($(document).scrollTop() + $(window).height() / 2 );
		//$(id).css('top',  winH/2-$(id).height()/2);
		//$(id).css('left', winW/2-$(id).width()/2);
		if(isIE(6)) $(MWindow).css({top:mTop2});
		$(MWindow).fadeIn('slow'); 
	});
	$('#close',MWindow).live('click',function(e) {
		e.preventDefault();
		$(MOverlay+','+MWindow).fadeOut('slow');
	});		
	$(MOverlay).live('click',function () {
		$('#close',MWindow).trigger('click');
	});
	
	return self;
}


