var popup_buynow_ready=false;
var i_extra_image=0;
var id_active=0;
var isGlobalSample=false;
jQuery(function(){
	popupBuyNowInitial();
});
function fillBuyNow(id,isSample){
	isGlobalSample=isSample;
	popupBuyNowReset();
	
	jQuery('#option_price input').val(isSample?p_price_sample[id]:p_price[id]);
	jQuery('#box_product_name').html(p_name[id]+" <span>["+p_model[id]+"]</span>");
	jQuery('#accordion_product a div').html(p_name[id]+" <span>["+p_model[id]+"]</span>");
	jQuery('#accordion_product_desc td').html(p_description[id]);
	if(getOptionSize(id)){
		jQuery('#option_size .option_right').html(getOptionSize(id));
		jQuery('#option_size').show();
	}
	else{jQuery('#option_size .option_right').empty();jQuery('#option_size').hide();}
	if(getColor(id)){
		jQuery('#option_color .option_right ul').html(getColor(id)).show();
	}
	reloadProductsImages(id);
	if(p_type_image[id].length>0)
	jQuery('#accordion_size_image').html('<table width="100%" height="100%"><tr><td valign="middle" align="center"><img src="images/size_chart/'+p_type_image[id]+'" alt="'+p_name[id]+'" title="'+p_name[id]+'" /></td></tr></table>');
	else
	jQuery('#accordion_size_image').empty();
	jQuery('#accordion_size_data').html(genHtmlSizeChart(id));
	jQuery('#option_qty input').val(!isSample?(mini_order_qty[id]==0?1:mini_order_qty[id]):1);
	
}
function popupBuyNowInitial(){
	jQuery('body').append('<div id="popup_buy_now"></div>');
	initEventOnResize();
	initEventOnScroll();
	jQuery('#popup_buy_now').unbind('popup_buy_now').load('popup_buy_now.tpl.html',function(){popup_buynow_ready=true;	
		//event
		jQuery('#accordion_size a').click(function(){
			var ele_new=jQuery(this).parent();
			var ele_old=jQuery('#accordion_product');	
			if(ele_new.height()<50){
				ele_new.animate(
							   {height:(jQuery.browser.msie?446:446)},
							   {
								   step:function(n,fx){
									   	  ele_old.css({height:((jQuery.browser.msie?474:474)-n)+'px'});
								   },
								   complete:function(){jQuery('#accordion_size a').removeClass('accordion_arrow_up').addClass('accordion_arrow_down');},
							   	   duration:500
							   });
			}else{
				ele_new=jQuery('#accordion_product');	
			 	ele_old=jQuery('#accordion_size');	
				ele_new.animate(
							   {height:(jQuery.browser.msie?448:448)},
							   {
								   step:function(n,fx){
									   ele_old.css({height:((jQuery.browser.msie?474:474)-n)+'px'});
								   },
								   complete:function(){jQuery('#accordion_size a').removeClass('accordion_arrow_down').addClass('accordion_arrow_up');},
							   	   duration:500
							   });
			}
		});	
		jQuery('#accordion_done a').click(function(){
			hidePopupBuyNow();							   
		});
		jQuery('#bt_add_to_cart').click(function(){
			//var params='action=save&buyproduct['+id+'][qty]='+(jQuery('#option_qty input').val());	
			//alert(color_selected_id[id_active]);
			chkQty(jQuery("#option_qty input"),id_active,isGlobalSample,function(){
					addCart(function(){
					jQuery('#accordion_product_option').hide();		
					jQuery('#bt_add_to_cart').hide();
					jQuery('#box_desc_added').fadeIn(500);
					jQuery('#bt_add_more').fadeIn(500);
				});																																		
			});
			
		});
		jQuery('#bt_add_more').click(function(){
			jQuery('#box_desc_added').hide();
			jQuery('#bt_add_more').hide();
			jQuery('#accordion_product_option').fadeIn(500);		
			jQuery('#bt_add_to_cart').fadeIn(500);	
		});
		
	});
	
}
function addCart(callback){
	var id=id_active;
	var params='action=save&buyproduct['+id+'][qty]='+jQuery('#option_qty input').val()+'&is_sample='+isGlobalSample;	
	if(jQuery('#option_size').css('display')=='block')
		params=params+''+'&buyproduct['+id+'][option]['+(p_options_id[id][color_selected_id[id]][(jQuery('#select_size_'+color_selected_id[id]+' option:selected').val())])+']='+(jQuery('#select_size_'+color_selected_id[id]+' option:selected').val());	
	if(p_color[id]!='')
		params=params+''+'&color_id='+color_selected_id[id];
		
	jQuery.ajax({
		   type: "POST",
		   url: "index.php",
		   data:params,
		   beforeSend:function(){ jQuery('#option_qty').addClass('loading_addcart');},
		   success: function(msg){
			   jQuery('#option_qty').removeClass('loading_addcart');
			   //alert(msg);
			   callback();
			   updateCartBoxCol();
		   }
		 });
	
}
function popupBuyNowReset(){
	jQuery('#accordion_size a').removeClass('accordion_arrow_down').addClass('accordion_arrow_up');
	jQuery('#accordion_product').height(448);
	jQuery('#accordion_size').height(26);
	jQuery('#box_desc_added').hide();
	jQuery('#bt_add_more').hide();
	jQuery('#accordion_product_option').show();		
	jQuery('#bt_add_to_cart').show();	
	if(p_color[id_active]!='')
		color_selected_id[id_active]=p_color_sort[id_active][0];
}
function popupBuyNow(id,isSample){
	if(popup_buynow_ready){
		id_active=id;
		fillBuyNow(id,isSample);
		showPopupBuyNow();
	}
}
function popupBuyNowPosition(){
	var poss=calBoxCenter(jQuery("#popup_buy_now").width(),jQuery("#popup_buy_now").height());
	jQuery('#popup_buy_now').css({left:poss.left+'px',top:poss.top+'px'});
}
function showPopupBuyNow(){
	showOverlay();
	popupBuyNowPosition();
	jQuery('#popup_buy_now').fadeIn(300);
}
function hidePopupBuyNow(){
	jQuery('#popup_buy_now').fadeOut(300,function(){hideOverlay();});
}
function showOverlay(f){
	if(jQuery('#overlay').length==0){
		jQuery('body').append('<div id="overlay"></div>');
		jQuery('#overlay').click(function(){hidePopupBuyNow();});
	}
	jQuery('#overlay').css({
						   	width:jQuery(document).width()+'px',
							height:jQuery(document).height()+'px'
							}).show();
}
function hideOverlay(f){
	jQuery('#overlay').hide();
}
function calBoxCenter(w,h){

		var window_w=jQuery(window).width();

		var window_h=jQuery(window).height();

		var window_scrolltop=jQuery(window).scrollTop();

		var window_scrollleft=jQuery(window).scrollLeft();

		var o={left:((window_w / 2)-(w/2)+window_scrollleft),top:((window_h / 2)-(h/2)+window_scrolltop)};
		
		if(window_w<w)
			o.left=-(w-window_w)+window_scrollleft;
		if(window_h<h)
			o.top=-(h-window_h)+window_scrolltop;	
		return o;

}
function initEventOnResize(){
	jQuery(window).resize(function(){
		jQuery("#overlay").css({'height':jQuery(document).height()+'px',width:jQuery(document).width()+'px'});
		jQuery('#popup_buy_now').stop();
		var poss=calBoxCenter(jQuery("#popup_buy_now").width(),jQuery("#popup_buy_now").height());
		jQuery('#popup_buy_now').animate({left:poss.left+'px',top:poss.top+'px'},{duration:500});	
	 });
}
function initEventOnScroll(){
	jQuery(window).scroll(function(){
		jQuery('#popup_buy_now').stop();
		var poss=calBoxCenter(jQuery("#popup_buy_now").width(),jQuery("#popup_buy_now").height());
		jQuery('#popup_buy_now').animate({left:poss.left+'px',top:poss.top+'px'},{duration:500});
	});
}
function reloadButtonExtraImage(id){


	if(i_extra_image>0)
		jQuery("#div-image-pre").show();
			else 
		jQuery("#div-image-pre").hide();
	if(i_extra_image<p_eimages[id][color_selected_id[id]].length)
		jQuery("#div-image-next").show();
	else 
		jQuery("#div-image-next").hide();

	
}
function getOptionSize(id){

	var txt_select='';
	if(p_options_name[id][color_selected_id[id]]!=''||p_options_name[id][color_selected_id[id]].length>0)
	{
			for(key in p_options_name[id][color_selected_id[id]])
				txt_select=txt_select+'<option value="'+key+'">'+p_options_name[id][color_selected_id[id]][key]+'</option>"';
			
			txt_select='<select id="select_size_'+color_selected_id[id]+'">'+txt_select+'</select>';
	}
	else return false;
	
	return txt_select;
}
function reloadProductsImages(id){
		jQuery('#box_images').html('<img style="display:none" src="images/'+(p_images[id][color_selected_id[id]]==''?'no-image.jpg':p_images[id][color_selected_id[id]])+'" alt="'+p_name[id]+'" border="0" '+(p_images[id][color_selected_id[id]]==''?'':'onmouseover="TJPzoom(this);return false;"')+' width="500" height="500" alt="Products Image" title=""><div id="div-image-pre" class="div-image-pre"></div><div id="div-image-next" class="div-image-next"></div>');

	jQuery('#box_images img').hide().unbind('load').load(function(){jQuery(this).fadeIn(300);})
	jQuery("#div-image-pre").mouseover(function(){
		jQuery(this).removeClass('div-image-pre');		
		jQuery(this).addClass('div-image-pre-active');		
	});	
	jQuery("#div-image-pre").mouseout(function(){
		jQuery(this).removeClass('div-image-pre-active');		
		jQuery(this).addClass('div-image-pre');									  
	});	
	jQuery("#div-image-next").mouseover(function(){
		jQuery(this).removeClass('div-image-next');		
		jQuery(this).addClass('div-image-next-active');	
	});	
	jQuery("#div-image-next").mouseout(function(){
		jQuery(this).removeClass('div-image-next-active');		
		jQuery(this).addClass('div-image-next');									   
	});
	if(p_eimages[id][color_selected_id[id]].length>0){
		i_extra_image=0;
		reloadButtonExtraImage(id)
	jQuery("#div-image-pre").click(function(){
										   i_extra_image--;
										    jQuery('#box_images img').hide();
											   if(i_extra_image==0)
												  jQuery('#box_images img').attr('src','images/'+p_images[id][color_selected_id[id]]);
											   else
												  jQuery('#box_images img').attr('src','images/'+p_eimages[id][color_selected_id[id]][i_extra_image-1]);
												  
												  jQuery('#box_images img').unbind('load').load(function(){jQuery(this).fadeIn(300);});
											   
											  // jQuery('#box_images img').fadeIn();
											   reloadButtonExtraImage(id);
										
										   });
	jQuery("#div-image-next").click(function(){
									     i_extra_image++;
										 var i=0;
										 jQuery('#box_images img').hide().attr('src','images/'+p_eimages[id][color_selected_id[id]][i_extra_image-1]).unbind('load').load(function(){jQuery(this).fadeIn(300);});
										 reloadButtonExtraImage(id);
										
									   });	
		
	}
}
function getColor(id){
	//alert(color_selected_id[id]);
	var str='';
	if(p_color[id]!=''){
	for(key in p_color_sort[id])
			str=str+'<li><span class="'+(color_selected_id[id]==p_color_sort[id][key]?'selected_color':'choice_color')+'" onmouseover="this.style.padding=\'3px 7px\'" onmouseout="this.style.padding=\'2px 6px\'" onclick="setSelectColor('+id+',\''+p_color_sort[id][key]+'\');this.className=\'selected_color\';" style="padding:2px 6px;cursor:pointer;background-color:'+(p_color[id][p_color_sort[id][key]].indexOf('#')!=-1?p_color[id][p_color_sort[id][key]]:'#'+p_color[id][p_color_sort[id][key]])+';line-height:20px;">&nbsp;</span></li>';
	}else return false

	return str;
}

function setSelectColor(id,color_id){
	color_selected_id[id]=color_id;
	//alert(id+'_'+color_selected_id[id]);
	jQuery('.selected_color').removeClass('selected_color').addClass('choice_color');
	i_extra_image=0;
	jQuery('#box_images img').hide().attr('src','images/'+(p_images[id][color_id]==''?'no-image.jpg':p_images[id][color_id]));
	
	if(p_images[id][color_id]==''){
		jQuery('#box_images img').attr('onmouseover','').unbind('mouseover');
	}else{
		jQuery('#box_images img').mouseover(function(){
		TJPzoom(this);
		return false;
		});
	}					
	if(getOptionSize(id)){
		jQuery('#option_size .option_right').html(getOptionSize(id));
		jQuery('#option_size').show();
	}else{jQuery('#option_size .option_right').empty();jQuery('#option_size').hide();}
	
	//jQuery('#box_images img').fadeIn();
	jQuery('#box_images img').unbind('load').load(function(){jQuery(this).fadeIn(300);})
	reloadButtonExtraImage(id);

}
function isEmptySizeChart(arr){
	for(key in arr){
		 for(key2 in arr[key]){
			 if(arr[key][key2].length>0)
			 return false
		}	
	}
	return true;
}
function genHtmlSizeChart(id){
	var output='';
	var tr_n=0,td_n=0;
	if(!isEmptySizeChart(p_type_value[id])){
		output=output+'<table cellspacing="0" cellpadding="0" border="0" width="100%" height="99">';
		for(key_tr in p_type_value[id]){
					output=output+'<tr>';
					td_n=0;
					for(key_td in p_type_value[id][key_tr]){
						if(tr_n<5)
						if(tr_n==0){
							if(td_n==0)
								output=output+'<td class="text-chart-b">&nbsp;'+p_type_value[id][key_tr][key_td]+'&nbsp;</td>';	
							else
								output=output+'<td class="text-chart-g">&nbsp;'+p_type_value[id][key_tr][key_td]+'&nbsp;</td>';
						}
						else{
							if(td_n==0)
								output=output+'<td class="text-chart-b">&nbsp;'+p_type_value[id][key_tr][key_td]+'&nbsp;</td>';
							else
								output=output+'<td class="text-chart">&nbsp;'+p_type_value[id][key_tr][key_td]+'&nbsp;</td>';
						}
					
						td_n++;
					}
					output=output+'</tr>';
					tr_n++;
		}
		output=output+'</table>';		
	}
	return output;
}

function chkQty(obj,id,isSample,ff){
	jQuery('#error_qty').hide().html(' ');
	var params_color=''
	if(p_color[id]!='')
		params_color=''+'&color_id='+color_selected_id[id];
	if(!isSample){
		jQuery.ajax({
		   type: "POST",
		   url: "index.php",
		   data: "ajax_action=chkMiniQty&id="+id+"&is_sample="+(isSample?1:0)+"&qty="+obj.val()+params_color,
		   success: function(msg){
			// alert( "Data Saved: " + msg );
				if(msg=='0'){
				 var f=function(){
				jQuery('#error_qty').fadeOut(300);
				}
				jQuery('#error_qty').html('-The minimum quantity for this item is '+mini_order_qty[id]+' pieces. <br>Please increase your quantity or buy a sample.').fadeIn(300);
				setTimeout(f,5000);
			 }else{
				 ff();
				}
		   }
		 });
	}else if(obj.val()==''||obj.val()<=0){
		obj.val(1);
		ff();
	}else{ff();}

/*jQuery('#error_qty').hide().html(' ');
	if(!isSample){
		if(parseInt(obj.val())<mini_order_qty[id]){
			var f=function(){
				jQuery('#error_qty').fadeOut(300);
			}
			jQuery('#error_qty').html('-The minimum quantity for this item is '+mini_order_qty[id]+' pieces. <br>Please increase your quantity or buy a sample.').fadeIn(300);
			setTimeout(f,5000);
			return false;
		}

	}else if(obj.val()==''||obj.val()<=0)
			obj.val(1);
			
	return true;*/
}