var currentSection, isDetail = false ;

$(window).load(function () {
	conheight();
	if($('#bg').length >0){	 
		var ImgSrc = $('#bg img').attr('src');
		var bgImg = new Image();
		bgImg.src = ImgSrc;	
		bgImg.onload = function(){			
		    //IE 
	    	bgImg.onload=function(){};
	    }
		
		bgImgWidth = bgImg.width;
		bgImgHeight = bgImg.height;	
		initBg(bgImgWidth, bgImgHeight);
	}
});


$(document).ready(function(){
	isDetail = ($('.detail-content').length > 0) ? true :false
	currentSection = $('body').attr('id');
	$('.container').height($(window).height());
	if($('#bg').length >0){	
		$('#bg img').hide();
		initBg();
		initRotateBg();
	}
	//console.log($(window).height() + ($(window).height()/100)*0.4 );
	conheight()
	$('.daily').click(function(){
		$('.dis-bg').height($('.contact-info').height()-10 );
		$('#distribution').animate({left: '382'},1000,'swing');
		
		return false;
	});
	$('.dis-close').click(function(){
		//$('#distribution').css('left',$(window).width);
		$('#distribution').animate({left: '2000'},600,'swing');
		return false;
	});
	$('.prod-detail-dathang').click(function(){
		$('#order').animate({left: '370'},1000,'swing');
		return false;
	});
	$('.order-close').click(function(){
		//$('#distribution').css('left',$(window).width);
		$('#order').animate({left: '2000'},600,'swing');
		return false;
	});
	
	$('.fancyitem').fancybox();
	if($('.prod-slider').length >0){
		prdGrSlider();
	};
	var search_default = "Tìm nhanh ...";
	var user_default = "User Name";
	var pass_default = "Password";
	$('.search-input').focus(function(){  
		if($(this).attr("value") == search_default) $(this).attr("value", ""); 
	});  
	$('.search-input').blur(function(){  
		if($(this).attr("value") == "") $(this).attr("value", search_default);  
	});
	$('.username').focus(function(){  
		if($(this).attr("value") == user_default) $(this).attr("value", ""); 
	});  
	$('.username').blur(function(){  
		if($(this).attr("value") == "") $(this).attr("value", user_default);  
	});
	$('.pass').focus(function(){  
		if($(this).attr("value") == pass_default) $(this).attr("value", ""); 
	});  
	$('.pass').blur(function(){  
		if($(this).attr("value") == "") $(this).attr("value", pass_default);  
	});
	
	$('.login_btn').click(function(){
		$(this).parent().find('.login-box').slideToggle(500);
		return false;
	});
	$('.main-nav li a').hover(function(){
		if(!$.browser.msie){
			$(this).fadeTo(100,0);
			$(this).fadeTo(400,1);
		}
	},function(){
		if(!$.browser.msie){
			$(this).fadeTo(100,0);
			$(this).fadeTo(200,1);
		}
	});
	
	if(!$.browser.msie){
		$('.cons-nav a').hover(function(){$(this).animate({opacity:1},300)},function(){$(this).animate({opacity:0.5},500)});
	} else{
		$('.login-sm').attr('value',"");
	}
	$('.search-sm').hover(function(){$(this).animate({opacity:0.5},200),$(this).animate({opacity:1},300)});
	
	$('.scr-content').tinyscrollbar();
	if( $('.prod-gallery').length >0){
		prdGallery();
	};
});

$(window).resize(function(){	
	if($('#bg').length >0){	initBg(bgImgWidth, bgImgHeight);}
	//console.log($(window).width());
	conheight();
});

function conheight(){
	var wh = $(window).height();
	
	if( wh>620){
		var ctH = (wh - $('.right-content').height()-70)/2;
		if(isDetail){
			$('.right-content').css('margin-top','15px');
		}else{
			$('.right-content').css('margin-top',Math.abs(ctH));
		}
		$('.container').height(wh);
	}else{
		if(!isDetail)$('.right-content').css('margin-top','10px')
		$('.container').height(620);
	}
	$('.scr-content').tinyscrollbar();
	if($('.cons-content').length >0){
		var conHeight = $('.right-content').height();
		//conHeight = parseInt(conHeight.replace("px",""));
		conHeight += 60;
		if(conHeight >410 && conHeight>wh){
			$('.container').height(conHeight);
			
		}

	}
}

function initBg( ImgW, ImgH){
	windowWidth  = $(window).width();
	windowHeight = $(window).height();
	bgImgWidth = ImgW;
	bgImgHeight = ImgH;
	
	scaleX = windowWidth/ImgW;
	scaleY = ImgH*scaleX;
	//$('#bg').css({ width: windowWidth, height: windowHeight});
	$('#bg').css({ height: windowHeight});
	if (windowWidth<ImgH){
		windowWidth=ImgH;
		scaleX = windowWidth/ImgW;
		scaleY = ImgH*scaleX;
	}
	$('#bg img').attr({ width: windowWidth/*, height: scaleY*/});
	
};


var bg_delayRotate = 6000;
var bg_animationSpeed = 1500;
var bg_tempRotateI = -1;
var bg_count_lastest;
var bg_autoRotate;

function initRotateBg(){
	//$('#bg img').hide();
	
	bg_count_lastest = $('#bg img').length;
	if (bg_count_lastest>1){
		bg_tempRotateI = bg_tempRotateI+1;
		if (bg_tempRotateI == bg_count_lastest) bg_tempRotateI=0;	
		rotateBg();
	}
}

function rotateBg(){
	$('#currentBg').text(bg_tempRotateI+1);
	
	$('#bg img').fadeOut(bg_animationSpeed);	
	//$('#bg img:eq('+bg_tempRotateI+')').delay(bg_animationSpeed).fadeIn(bg_animationSpeed);
	$('#bg img:eq('+bg_tempRotateI+')').fadeIn(bg_animationSpeed);
	
	
	if (bg_count_lastest>1) bg_autoRotate=setTimeout("initRotateBg()", bg_delayRotate)	
};


//////////////////////////product gallery////////////////////
function prdGallery(){
	var crrpd =0;
	var bigimg=0;
	var p = 0;
	$('.prod-gallery-wrap').append('<div class="thumb-mask"></div>');
	$('.thumb-mask').append($('.glr').clone().addClass('prdthumb').removeClass('glr'));
	var sumli = $('.glr li').length;
	$('.glr').css("width",sumli*390);
	//$('.glr a').removeAttr('href');
	$('.glr a').each(function(){
		var href = $(this).attr('href');
		if(href=='')
			$(this).removeAttr('href');	
	});
	
	$('.prdthumb').css("width",sumli*58);
	if(sumli >5){
		$('.prdthumb').animate({marginLeft:((sumli-2)*58)*-1},sumli*1500,'linear',replaythumb);
		$('.prod-gallery-wrap').append('<a href="javascrip:;" id="thumb-left">Left</a><a href="javascrip:;" id="thumb-right">right</a>');
	}	
	
	$('.prod-gallery-wrap').append('<div class="thumb-bg"></div>');
	$('.prdthumb li').each(function(i){
		$(this).attr("rel",i)
		$(this).children().find('img').css({height:48, width:48});
		$(this).children().attr("href","#");
		$(this).hover(function(){
			$(this).animate({opacity:0.5},100);
			$('.prdthumb').stop(true);
		},function(){
			$(this).animate({opacity:1},200);
			var loff =sumli -  $(this).attr('rel');
			if($('.prdthumb').children().length >5){
				$('.prdthumb').animate({marginLeft:((sumli-2)*58)*-1},loff*1500,'linear',replaythumb);
			}
		});
	});
	$('#thumb-right').click(function(){
		thumplay("next",true);
		return false;
	});
	$('#thumb-left').click(function(){
		thumplay("prev",true);
		return false;
	});
	$('.prdthumb li').click(function(){
		var newp = $(this).attr("rel");
		var diff = Math.abs(bigimg-newp);
		bigimg = newp;
		var speed = diff*400;
		offset = newp*387*-1;
		$('.glr').animate({marginLeft: offset},{ queue:false, duration:speed, easing:'swing' });
		return false;
	});
	function replaythumb(){
		$('.prdthumb').animate({marginLeft:0},1000,'linear',function(){
			$('.prdthumb').animate({marginLeft:((sumli-2)*58)*-1},sumli*1500,'linear',replaythumb);
		});
		
	}
	function thumplay(dir,cl){
		if(crrpd == 0) crrpd = 1;
		if(crrpd == sumli - 6 ) crrpd--;
		//console.log(crrpd);
		p= crrpd;
		switch(dir){
			case "next":
				crrpd++;
				break; 
			case "prev":
				crrpd--;
				break; 
			default:
				crrpd = dir;
				break; 
		};
		$('.prdthumb').stop(true);
		var diff = Math.abs(p-crrpd);
		var speed = diff*500;
		offset = crrpd*58*-1;
		$('.prdthumb').animate({marginLeft: offset},{ queue:false, duration:speed, complete:pjaj,easing:'swing' });
		
	}
	pjaj();
	function pjaj(){
		if(sumli >5){
			$('#thumb-left').show();
			$('#thumb-right').show();
		}
		
		/*if ((crrpd ==(sumli-6)) || (sumli <=6)){
			$('#thumb-right').hide();
		}
		if (crrpd <= 0){
			$('#thumb-left').hide();
		}*/
		
	}
}

//////////////////////////product slider ////////////////////
var crrGr =0;
var totalGr = 0;
var canNext = false;
var canPrev = false;
var ovGr =0;
function prdGrSlider(){
	var speedScroll=1000;
	totalGr = $('.prod-gr').length;
	var liWidth = $('.prod-slider li').css("width");
	liWidth = parseInt(liWidth.replace("px",""));
	liWidth +=5;
	if($('.prod-group').length >0 ){
		ovGr = 3;
	} else{
		ovGr = 4;
	}

	var crrwidth = $(window).width();
	if (crrwidth <1100){
		$('.prod-overlay').css('left','514px');
		$('.prod-next').css('left','560px');
		ovGr = 2;
	}
	$('.prod-slider').width((totalGr+2) * (liWidth));
	
	//console.log(ovGr);
	var group_id = $('#group_id').val();
	
	if(group_id>0)
		crrGr = (readCookie('current_item_' + ovGr + '_' + group_id));
	else
		crrGr = (readCookie('current_item_' + ovGr));
	
	
	if(crrGr<0)
	{
		$('.prod-slider').animate({left: liWidth * crrGr + 'px'}, speedScroll, 'swing',checkSliderCtrl());
	}
	
	checkSliderCtrl();
	$('.prod-next').click(function(){
		if(canNext){
			crrGr--;
			
			if(group_id>0)
				writeCookie('current_item_' + ovGr + '_' + group_id,crrGr );
			else
				writeCookie('current_item_' + ovGr,crrGr );
				
						
			$('.prod-slider').animate({left:'-=' + liWidth + 'px'}, speedScroll, 'swing',checkSliderCtrl());
			return false;
		};
	});
	$('.prod-prev').click(function(){
		if(canPrev){
			crrGr++;
			
			if(group_id>0)
				writeCookie('current_item_' + ovGr + '_' + group_id,crrGr );
			else
				writeCookie('current_item_' + ovGr,crrGr );
				
						
			$('.prod-slider').animate({left:'+=' + liWidth + 'px'}, speedScroll, 'swing',checkSliderCtrl());
			return false;
		};
	});
	if (isIpad()){
		var stX = fnX = 0;
		var osl = false;
		speedScroll=1500;
		$('.container').bind("touchstart", tStart);
		$('.container').bind("touchmove", tEnd);
		function tStart(event){
			var e = event.originalEvent;
	        stX = e.targetTouches[0].pageX;
			osl = true
		}
		function tEnd(event){
			var e = event.originalEvent;
	        fnX = e.targetTouches[0].pageX;
			//var fnX = e.targetTouches[0].pageX - startX;
			if((stX >fnX)&& osl){
				$('.prod-next').trigger('click');
				osl = false;
			}else if((stX <fnX)&& osl){
				$('.prod-prev').trigger('click');
				osl = false;
			};
		}
	}
}
function isIpad(){
	return navigator.platform == "iPad";
}
function checkSliderCtrl(){
	
	if( crrGr>=0){
		canNext = true;
		canPrev = false;
	};
	if( crrGr<0  ){
		canNext = true;
		canPrev = true;
	};
	
	
	if( crrGr==-(totalGr - ovGr) ){
		canNext = false;
		canPrev = true;
	};
	$('.prod-prev').css("display","none");	
	$('.prod-next').css("display","none");	
	if(canNext){
		$('.prod-next').css({"display":"block","opacity":0.5});	
		$('.prod-next').hover(function(){$(this).animate({opacity:1},100)},function(){$(this).animate({opacity:0.5},200)});	
	}
		
	if(canPrev){
		$('.prod-prev').css({"display":"block","opacity":0.5});	
		$('.prod-prev').hover(function(){$(this).animate({opacity:1},100)},function(){$(this).animate({opacity:0.5},200)});	
	}
	//console.log(totalGr);
}

//cookie
function writeCookie(name,value,days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
            }else{
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for(i=0;i < ca.length;i++) {
        c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return '';
}


