// JavaScript Document
var news_obj;
var index = 0;
var videoCon = '';
var scrollLoading = false;

// loading animation
$.tools.overlay.addEffect("drop", function(css, done) { 
   
   // use Overlay API to gain access to crucial elements
   var conf = this.getConf(),
       overlay = this.getOverlay(); 
   
   // determine initial position for the overlay
   css.top += $(window).scrollTop();
   css.left += $(window).scrollLeft()+800;
   css.position = 'absolute';
   
   // position the overlay and show it
   overlay.css(css).show();
   
   // begin animating with our custom easing
   overlay.animate({ left: '-=800',  opacity: 1 }, {duration: 500, easing: 'easeOutBack'});
   
   /* closing animation */
   }, function(done) {
	  //this.getOverlay().animate({left:'-=800', opacity:0, 'z-index':9999}, {duration: 500, easing: 'easeInBack', complete: function() { $(this).hide(); done.call(); } });
	  this.getOverlay().animate({left:'-=800', opacity:0, 'z-index':9999}, 500, function() { $(this).hide(); done.call(); });
   }
);

function isSet(variable) {
	return( typeof( variable ) != 'undefined'  && variable != null);
}

function hrefPageEffect() {
	var ulink = $(this).attr('link');
	if (isSet(ulink)) {
		$('.wrap').trigger('click');
		$('.wrap').masonry({resizeable: false});
		$('.box .effect').fadeOut('slow', function() { redirect(ulink); });
	}
}

function redirect(ulink) {
	window.location=ulink;
}

function fixPapeHeightForIE6 () {
	if (IE6)  {
		var height = $('#heightControl').height();
		//alert(height +'<'+ ($(window).height()-65));
		if (height < $(window).height()-65) {
			$('#heightControl').height($(window).height()-65);
		}
	}
}

function fixPapeHeight() {
	$('#heightControl').css({'min-height':$(window).height()-65})
}

function findParent(current, targetCssClass) {
	var parent = current.parent();
	if(parent.hasClass(targetCssClass))
		return parent;
	else
		return findParent(parent, targetCssClass)
}

function searchResult() {
	var val = $(this).val();
}

function showSearchBox() {
	try {
		clearTimeout(menuItemFilierController);
	}
	catch(e) {}
	if ($(this).next().is(':hidden')) {
		$(this).next().show(500);
	}
	else {
		$(this).next().hide(500);
		setTimeout("hideBox()", 400);
	}
	$('.wrap').trigger('click');
}

function hideBox(obj) {
	$('.selectBoxMain').hide();
}

function showmagnifierBoxClose() {
	var obj = $('#selectKeyword');
	if (obj.width() > 100) {
		searchText = obj.val();
		obj.parent().animate({
    		width: 28
  		}, 500);
		obj.animate({
    		width:0
  		}, 500, function () { obj.removeClass('magnifierBorder'); });
		if ($('.magnifierResult').is(':visible')) {
			setTimeout("$('.magnifierResult').hide('blind', 400)", 100);
		}
		obj.val('');
	}
}

function showmagnifierBox() {
	try {
		clearTimeout(menuItemFilierController);
	}
	catch(e) {}
	var obj = $('#selectKeyword');
	if (obj.width() < 100) {
		//$('.top-search-box .selectBoxMain').hide(500);
		objSearchBox = $('.top-search-box .selectBoxMain');
		if (objSearchBox.is(':visible')) {
			objSearchBox.hide(500);
			setTimeout("hideBox()", 400);
		}
		obj.val(searchText);
		obj.parent().animate({
    		width: 180
  		}, 500)
		obj.addClass('magnifierBorder');
		obj.animate({
    		width: 150
  		}, 500, function () { obj.focus() });
		
		if (searchText != '') {
			$('.magnifierResult').show('blind', 500);
		}
	}
}

function moveUnderDiv(obj, boxHeight) {
	if (obj.next().html() != null) {
		var position = obj.next().position();
		obj.next().animate({top:(position.top+boxHeight)}, speed);
		moveUnderDiv(obj.next(), boxHeight);
	}
}

function clickOtherBox(dataID) {
	$('[dataID="'+dataID+'"]').trigger('click');
}

function showContentBox() {
	news_obj = $(this);
	var dataID = news_obj.attr('dataID');
	if (gDataID == dataID) {
		return;
	}
	else if (!$('.detailBox').hasClass('hidden')) {
		$('.detailBox .closeBtn').trigger('click');
		setTimeout("clickOtherBox('"+dataID+"')", speed+200);
		return;
	}
	
	gDataID = dataID;
	$('#loading').show();	
	$.ajax({
          type: "POST",
          url: 'ajax/loadNewsDetail.php',
          data: {nid:dataID},
		  dataType: 'json',
          success: function(data) {
		  	  try {
			  	$('.wrap').masonry({resizeable: false});
			  	$('#loading').hide();
			  	$('.detailBoxMain .content').html(data.con);
			    
				videoCon = data.video;
				
			  	setTimeout("callBackFormNew()",250);
			  }
			  catch(e) { $('#loading').hide(); gDataID = ''; }
          },
		  error: function(msg) {
			$('#loading').hide();
			gDataID = '';
		  }
    });
}

function callBackFormNew() {
	var p_obj = findParent(news_obj,'box');
	var obj = findLargeLeftObj(p_obj, p_obj);
	var obj2 = $('.detailBoxMain')
	var height = obj2.height();
	var position = obj.position();
	var p_position = p_obj.position();
			  
	if (obj.height()+position.top < p_obj.height()+p_position.top)
		var boxHeight = p_obj.height()+p_position.top+50;
	else
		var boxHeight = obj.height()+position.top+50;
	
	obj2.find('.detailBox').hide().removeClass('hidden');
	obj2.css({'top':(boxHeight)});
			  
	$('.newsContent').unbind('click');
	
	var addPadding = 20;
	
	if (videoCon != '')
		addPadding += 270;
	
	$('.wrap').animate({height:($('.wrap').height()+height+addPadding)}, speed);
	moveUnderDiv(obj, height+addPadding);
	
	obj2.find('.detailBox').show('blind', 500, function () { moveToFuns($(this)); $('.newsContent').click(showContentBox); loadVideo(); });
}

function loadVideo() {
	if (videoCon != '') {	
		$('.detailBoxMain .content').append(videoCon);
		VideoJS.setupAllWhenReady();
		videoCon = '';
		autoPlay();
	}
}

function autoPlay() {
	var video = $("#example_video_1").get(0);
	video.load();
	video.player.play();
}

function moveToFuns (_obj) {
	var position = _obj.offset();
	$(document).scrollTo(position.top, speed);
}

function findLargeLeftObj(_obj, o_obj) {
	var obj = _obj
	var o_height = o_obj.height();
	var o_position = o_obj.position();
	var position_next = _obj.next().position();
	
	if (position_next != null) {
		if ((o_height+o_position.top) > (position_next.top)) {
			obj = findLargeLeftObj(obj.next(), o_obj);
		}
	}
	return obj;
}

function showAllDiv2(num, status) {
	var obj = $('div.effect:eq('+num+')');
	if (obj.html() != null && obj.hasClass('hidden')) {
		if ($('div.effect:eq('+(num+1)+')').html() != null) {
			obj.hide().removeClass('hidden').fadeIn(500);
			num++;
			setTimeout("showAllDiv2("+num+", '"+status+"')", 200);
		}
		else {
			obj.hide().removeClass('hidden').fadeIn(500, function () { if (IE6) { $('.effect').css({zoom:0}); }; if (status == 'run_bind') { showEnd(); }; });
		}
	}
}

function showEnd() {
	if (IE6) {
		$('.effect').css({zoom:0});
	}
	
	try {
		for (i in endEffectRunFunsClickHeader) {
			$(i).bind('click', eval(endEffectRunFunsClickHeader[i]));
		}
	}
	catch(e) {};
	
	$('.wrap').masonry({resizeable: true}, function() { $('.wrap').css({'overflow':'visible'}); });
	
	try {
		for (i in endEffectRunFunsClick) {
			$(i).bind('click', eval(endEffectRunFunsClick[i]));
		}
	}
	catch(e) {};
	
	try {
		for (i in endEffectRunFunsMouseOver) {
			$(i).bind('mouseover', eval(endEffectRunFunsMouseOver[i]));
		}
	}
	catch(e) {};
	
	try {
		for (i in endEffectRunFunsMouseOut) {
			$(i).bind('mouseout', eval(endEffectRunFunsMouseOut[i]));
		}
	}
	catch(e) {};
	
	try {
		for (i in endEffectRunFunsChange) {
			$(i).bind('change', eval(endEffectRunFunsChange[i]));
		}
	}
	catch(e) {};
	
	menuItemFilierController = setTimeout("triggerClickFilier()", 10000);
}

function loadingSetCenter() {
	$('#loading').css({top: ($(window).height()/2+$(window).scrollTop()-35), left:($(window).width()/2+$(window).scrollLeft()-35)});
}

function bindSet() {
	if ($(".scrollable").html != '') {
		$(".scrollable").scrollable({
			vertical: true,
			keyboard: false,
			speed: 1000,
			onSeek:function (event, i) {
				index = i;
				if (i == 0) {
					$('#custom .topBtn').hide();
				}
				else {
					$('#custom .topBtn').show();
				}
				
				if (i == $('.scrollable .item:not(.cloned)').length-1) {
					$('#custom .downBtn').hide();
				}
				else {
					$('#custom .downBtn').show();
				}
			}
		});
	 
		//$('.scrollable div:first').css({top:-573});
	
		$('#custom .topBtn').bind('click', function () {
			if (index == 0)
				return;
			$(this).show();
			$("#custom .small_photo").flip({
				direction:'bt',
				color: '#FFFFFF',
				speed: 500,
				onBefore: function () {
					$('.prev').trigger('click');
				
					if (index-1 < 0)
						var i = $('.scrollable .item:not(.cloned)').length-1;
					else
						var i = index-1;
					
					//alert((index+1)+' > '+($('.scrollable .item:not(.cloned)').length-1));
					var html_image = $('.scrollable .item:not(.cloned):eq('+i+') .image').html();
					html_image = $(html_image);
					html_image.width(142);
					html_image.height(107);
					$('#custom .small_photo').html(html_image);
				}
			});
		})
	
		$('#custom .downBtn').bind('click', function () {
			if (index == $('.scrollable .item').length-1)
				return;
			
			if (index-2 == $('.scrollable .item').length)
				return;
			$("#custom .small_photo").flip({
				direction:'tb',
				color: '#FFFFFF',
				speed: 500,
				onBefore: function () {
					$('.next').trigger('click');
				
					if (index+1 > $('.scrollable .item').length-1)
						var i = 0;
					else
						var i = index+1;
					
					//alert((index+1)+' > '+($('.scrollable .item:not(.cloned)').length-1));
					var html_image = $('.scrollable .item:not(.cloned):eq('+i+') .image').html();
					html_image = $(html_image);
					html_image.width(142);
					html_image.height(107);
					$('#custom .small_photo').html(html_image);
				}
			});
		})
	
		//mousewheel events - down / up button trigger the scroll down / up
		$('.scrollable').mousewheel(function(e, delta) {
			if($('.scrollable .items').is(':animated'))
				return false;
							
			if(delta > 0) {
				$('#custom .topBtn').trigger('click');
			}
			else {
				$('#custom .downBtn').trigger('click');
			}
		
			return false;
		});
	}
}

function loadProjectDetailBox() {
	$('#loading').show();
	var pid = $(this).attr('data');
	$.ajax({
    	type: "POST",
    	url: 'ajax/loadProjectDetail.php',
    	data: {pid:pid},
		dataType: 'json',
		cache: false,
    	success: function(data){
			try {
				$('#loading').hide();
				if (data.con != '') {
					$('#custom .reference-con').html(data.con);
					setTimeout("bindSet()", 250);
					$('#overlayBtn').trigger('click');
				}
			}
			catch(e) {
				$('#loading').hide();	
			}
    	},
		error: function(msg) {
	  		$('#loading').hide();
		}
	});
}

function printObj(obj) {
  var str = ''; //variable which will hold property values
  if (isArray(obj))
  {
    for(prop in obj)
    {
	  if (isArray(obj[prop]))
	    str += prop+" value :\n{"+printObj(obj[prop])+"}\n";
	  else
	    str += prop+" value :"+obj[prop]+"\n";//Concate prop and its value from object
    }
  }
  else
    str = obj;
  return str;
}

function isArray(obj) {
  return typeof(obj) == 'object';
}

function changeCategoryBox(status) {
	var obj = $('#category_container li.selected');
	var id = obj.attr('id');
	id = id.split('_');
	id = id[id.length-1];
	$('#sub_category_container li:hidden').css({display:'block'});
	if (id != '')
		$('#sub_category_container li:not(:first):not([parent_id="'+id+'"])').css({display:'none'});
	if (status != 'first')
		$('#sub_category_container li:first').trigger('click');
}

function changeFilierBox() {
	$(document).unbind('scroll');
	$(window).unbind('resize');
	$('.closeBtn').trigger('click');
	var data = fixSelectBoxName($(this).attr('id'));
	if (data['name'] != 'finishes_input' && data['name'] != 'color_input') {
		$('#color_container li').removeClass('selected');
		$('#color_container li:first').addClass('selected');
		$('#color_input').val($('#color_container li:first').html());
		$('#finishes_container li').removeClass('selected');
		$('#finishes_container li:first').addClass('selected');
		$('#finishes_input').val($('#finishes_container li:first').html());
	}
	else if (data['name'] == 'color_input') {
		$('#finishes_container li').removeClass('selected');
		$('#finishes_container li:first').addClass('selected');
		$('#finishes_input').val($('#finishes_container li:first').html());
	}
	var category_id = $('#category_container li.selected').attr('id');
	category_id = category_id.split('_');
	category_id = category_id[category_id.length-1];
	var sub_category_id = $('#sub_category_container li.selected').attr('id');
	sub_category_id = sub_category_id.split('_');
	sub_category_id = sub_category_id[sub_category_id.length-1];
	var color_id = $('#color_container li.selected').attr('id');
	color_id = color_id.split('_');
	color_id = color_id[color_id.length-1];
	var finishs_id = $('#finishes_container li.selected').attr('id');
	finishs_id = finishs_id.split('_');
	finishs_id = finishs_id[finishs_id.length-1];
	//alert(category_id+'/'+sub_category_id+'/'+color_id+'/'+finishs_id);
	
	if (category_id == '' && sub_category_id == '' && color_id == '' && finishs_id == '')
		return;
	
	$('#loading').show();
	$.ajax({
    	type: "POST",
    	url: 'ajax/itemFilier.php',
    	data: {category_id:category_id, sub_category_id:sub_category_id, color_id:color_id, finishs_id:finishs_id},
		dataType: 'json',
		cache: false,
    	success: function(data){
			$('#loading').hide();
			$('.wrap').masonry({resizeable:false});
			if ($('.box:not(.main)').length != 0) {
				$('.box:not(.main)').fadeOut(speed);
				$('.box:last').fadeOut(speed, function() { $('.box:not(.main)').remove(); $('.wrap').append(data.con); changeFilierBoxEndLoad(); });
				changeColorFinishsBox(data.color, data.finish);
			}
			else {
				$('.wrap').append(data.con);
				changeFilierBoxEndLoad();
			}
			$('#scroll_data').val(category_id+'*'+sub_category_id+'*'+color_id+'*'+finishs_id);
			$('#scroll_data').attr('count', data.num);
    	},
		error: function(msg) {
	  		$('#loading').hide();
		}
	});
}

function changeColorFinishsBox(color, finish) {
	$('#finishes_container li:not(:first)').hide();
	for (i in finish) {
		$('#finishes_container li[id="finishes_input_'+i+'"]').show();
	}
	$('#color_container li:not(:first)').hide();
	for (i in color) {
		$('#color_container li[id="color_input_'+i+'"]').show();
	}
}

function changeFilierBoxEndLoad() {
	$('.wrap').masonry({resizeable: true}, function() { $('.wrap').css({'overflow':'visible'});  showAllDiv2(1, ''); setBindProproduct(); });
}

function fixSelectBoxName(_name) {
	var temp = _name.split(/[\s_]+/);
	var count = temp.length;
	var name = '';
	for (i=0; i < count-1; i++) {
		if (name != '')
			name += '_';
		name += temp[i];
	}
	var id = temp[count-1];
	
	return {id:id, name:name};
}

function setBindProproduct() {
	$('.box:not(.main)').bind("click.product", loadProductDetailBox);
	
	if ($(document).height() < $(window).height()+150) {
		if (!scrollLoading) {
			scrollLoading = true;
			scrollLoader();
		}
	}
	
	$(window).scroll(function(){
		//alert(($(window).scrollTop()+50) + '>' + ($(document).height()-$(window).height()));
		if ($(window).scrollTop()+150 > $(document).height() - $(window).height()){
			if (!scrollLoading) {
				scrollLoading = true;
				scrollLoader();
			}
		}
	});
	
	$(window).resize(function(){
		if ($(window).scrollTop()+150 > $(document).height() - $(window).height()){
			if (!scrollLoading) {
				scrollLoading = true;
				scrollLoader();
			}
		}
	});
}

function scrollLoader() {
	if ($("#scroll_data").attr('count') != 'end') {
		$('#loading').show();
		$.ajax({
          type: "POST",
          url: 'ajax/scrollLoader.php',
          data: {data: $("#scroll_data").val(), num:$("#scroll_data").attr('count')},
		  dataType: 'json',
          success: function(data) {
			$('#loading').hide();
			scrollLoading = false;
			$('.wrap').append(data.con);
			$('#scroll_data').attr('count', data.num);
			$('.wrap .box .effect').removeClass('hidden');
			$('.wrap').masonry();
			setTimeout('setBindScrollLoder()', 250);
          },
		  error: function(msg) {
			$('#loading').hide();
			scrollLoading = false;
		  }
        });
	}
	else {
		scrollLoading = false;
	}
}

function setBindScrollLoder() {
	$('.box:not(.main)').unbind("click.product");
	$('.box:not(.main)').bind("click.product", loadProductDetailBox);
}

function setBlind(project, product) {
	if ($('.PhotoMain').html() != '') {
		if (project > 3) {
			$('.PhotoMain').scrollable({circular: true, mousewheel: true, keyboard: true, speed: 1000});
			$('.PhotoMain .nextBtn').bind("click", function() { $('.PhotoMain').data("scrollable").next(); });
			$('.PhotoMain .prevBtn').bind("click", function() { $('.PhotoMain').data("scrollable").prev(); });
		}
		$('.PhotoMain .items .item div').mouseover(showMainPhoto);
		$('.PhotoMain .items .item div').mouseout(hiddenMainPhoto);
	}
	
	if (product > 3) {
		$('.otherProduct').scrollable({circular: true, mousewheel: true, keyboard: true, speed: 1000});
		$('.otherProduct .nextBtn').bind("click", function() { $('.otherProduct').data("scrollable").next(); });
		$('.otherProduct .prevBtn').bind("click", function() { $('.otherProduct').data("scrollable").prev(); });
	}
}

function showProductDetail(obj) {
	var id = $(obj).attr('showId');
	$('.product-description').hide();
	$('.product-description[showId="'+id+'"]').show();
}

function hiddenProductDetail() {
	$('.product-description').hide();
}

function loadProductDetailBox() {
	$('#loading').show();
	/*if ($(this).attr('searchBox') == 'on') {
		try {
			clearTimeout(showmagnifierBoxController);
		}
		catch(e) {}
	}*/
	var pid = $(this).attr('data');
	var addCart = $(this).attr('addCart');
	$.ajax({
    	type: "POST",
    	url: 'ajax/loadProductDetail.php',
    	data: {pid:pid, addCart:addCart},
		dataType: 'json',
		cache: false,
    	success: function(data){
	  		try {
				$('#loading').hide();
				if (data.con != '') {
					$('#custom2 .product_detail_content').html(data.con);
					$('#overlayBtn2').trigger('click');
					setTimeout("setBlind("+data.project+","+data.product+")", 250);
				}
			}
			catch(e) {
				$('#loading').hide();	
			}
    	},
		error: function(msg) {
	  		$('#loading').hide();
		}
	});
}

function loadOtherProduct(pid, addCart) {
	$('#loading').show();
	$('#custom2').animate({left:-800}, 'slow');
	$.ajax({
    	type: "POST",
    	url: 'ajax/loadProductDetail.php',
    	data: {pid:pid, addCart:addCart},
		dataType: 'json',
		cache: false,
    	success: function(data){
	  		try {
				$('#loading').hide();
				if (data.con != '') {
					$('#custom2 .product_detail_content').html(data.con);
					var temp = $(window).width()/2-$('#custom2').width()/2;
					$('#custom2').animate({left:$(window).width()}, 0, function () { $('#custom2').animate({left:temp}, 'slow', function () {  /*if (!IE6) $('#custom2').effect('bounce', {direction:'left', distance: 40, times: 1}, 200);*/ }); });
					setTimeout("setBlind("+data.project+","+data.product+")", 250);
				}
			}
			catch(e) {
				$('#loading').hide();
				$('#custom2 .close').trigger('click');
			}
    	},
		error: function(msg) {
	  		$('#loading').hide();
			$('#custom2 .close').trigger('click');
		}
	});
	
}

function showMainPhoto() {
	try {
		clearTimeout(controllerMainPhotoChange);
	}
	catch (e) {}
	var index = $(this).attr('index');
	controllerMainPhotoChange = setTimeout("showMainPhotoTimeOut('"+index+"')", 300);
}

function showMainPhotoTimeOut(index) {
	$('.mainPhoto .img:visible').fadeOut(500);
	$('.mainPhoto .img:eq('+index+')').fadeIn(500);
}

function hiddenMainPhoto() {
	try {
		clearTimeout(controllerMainPhotoChange);
	}
	catch (e) {}
	controllerMainPhotoChange = setTimeout("hiddenMainPhotoTimeOut()", 300);
}

function hiddenMainPhotoTimeOut() {
	$('.mainPhoto .img:visible').fadeOut(500);
	$('.mainPhoto .img:first').fadeIn(500);
}

function addToCart(pid) {
	$.ajax({
    	type: "POST",
    	url: 'ajax/cartEvent.php',
    	data: {pid:pid, status:'add'},
		dataType: 'json',
		cache: false,
    	success: function(data){
	  		try {
				if (data.check) {
					$(".cart .addToCartMess").html(data.con);
				}
			}
			catch(e) {
				$(".cart .addToCartMess").html('error!');
			}
    	},
		error: function(msg) {
	  		$(".cart .addToCartMess").html(data.con);
		}
	});
}

function realTimeSearchTimeOut() {
	try {
		clearTimeout(realTimeSearchController);
	}
	catch (e) {}
	var keyword = $(this).val();
	if (keyword != '')
		realTimeSearchController = setTimeout("realTimeSearch('"+keyword+"')", 600);
	else
		$('.magnifierResult').hide('blind', 500);
}

function realTimeSearch(keyword) {
	$('#loading').show();
	$.ajax({
    	type: "POST",
    	url: 'ajax/realTimeSearch.php',
    	data: {keyword:keyword},
		dataType: 'json',
		cache: false,
    	success: function(data){
	  		try {
				$('#loading').hide();
				$('.magnifierResult .magnifierResult-footer a').attr('link', 'search.php?keyword='+keyword);
				if ($('.magnifierResult').is(':visible')) {
					$('.magnifierResult').hide('blind', 500, function() {
						$('.magnifierResult .magnifierResult-content').html(data.con);
						$('.magnifierResult').show('blind', 500, function () { $('.magnifierResult a').click(loadProductDetailBox); });
					});
				}
				else {
					$('.magnifierResult .magnifierResult-content').html(data.con);
					$('.magnifierResult').show('blind', 500, function() { $('.magnifierResult a').click(loadProductDetailBox); });
				}
			}
			catch(e) {
				$('#loading').hide();
			}
    	},
		error: function(msg) {
	  		$('#loading').hide();
		}
	});
}

function triggerClickFilier() {
	$('.sort_box').trigger('click');
}
