/*
* Load popup 
* copyright Cetus
* author 
*/

var http_root = "http://physiolac.vn/";		  
var tb_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
var warningContent = "<img src='" +http_root+ "Views/zenko/images/info_icon.png' height='65' hspace='5' style='margin-right:5px;' vspace='5' align='left' border='0' />Xin lưu ý đây chỉ là thông tin tham khảo dành cho cán bộ y tế. Vui lòng click xác nhận nếu là cán bộ y tế và có nhu cầu tìm hiểu thêm thông tin sản phẩm.";
var caption = 'Trước khi bạn tiếp tục...';

//on page load call tb_init
$(document).ready(function(){
	tb_init('a.thickbox, area.thickbox, input.thickbox, div.thickbox');//pass where to apply thickbox
	tb_init2('a.share_video');
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

function checkYoutubeID(url) {
	i = url.indexOf("youtube.com/user");
	if (i != -1) {		
		url = "http://www.youtube.com/watch?v=" + url.substring(url.lastIndexOf("/") + 1, url.length) + "&feature=related";
	}
	return url;
}

function youtubeIDextract(url) { 
	var youtube_id; 
	youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1"); 
	return youtube_id; 
}

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
		var t = null;
		var a = this.id || this.alt;
		var g = this.href || false;
		caption = "Physiolac.Vn - Thông báo";
		tb_show('',a,'icon.gif',caption,warningContent);
		$("#TB_ajaxContent").css('background','none');
		return false;
	});
}

function tb_init2(domChunk){
	$(domChunk).click(function(){
		var t = null;
		var a = this.id || this.alt;
		var g = this.href || false;
		i = g.indexOf("?v=",0) + 3;
		j = g.indexOf("&",i) != -1 ? g.indexOf("&",i) : g.length;
		g = checkYoutubeID(g);
		yid = youtubeIDextract(g);		
		//warningContent = g +"<br />"+ yid;
		warningContent = "<iframe width='100%' height='450px' src='http://www.youtube.com/embed/" +yid+ "' frameborder='0' allowfullscreen></iframe>";
		caption = 'Physiolac.vn - Video Clip';		
		tb_show(t,a,g,caption,warningContent);
		this.blur();
		$("#TB_closeAjaxWindow").remove();
		$("#TB_ajaxWindowTitle").css({'padding':'10px 0px 5px 10px'});
		$("#TB_window").css({'width':'750px','margin-left':'-350px','margin-top':'-250px'});
		$("#TB_ajaxContent").css({'width':'','height':'','padding':'0px','background':'url(Views/zenko/images/pr_top.png) no-repeat bottom center'});
		return false;
	});
}

function tb_show(title, url, imageGroup, caption, warningContent) {//function called when the user clicks on a thickbox link
	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6			
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'></div>");//add loader to the page
		$('#TB_load').show();//show loader	
		
		
		var queryString = imageGroup.replace(/^[^\?]+\??/,'');
		var params = tb_parseQuery( queryString );
		var ajaxTitle='';
		TB_WIDTH = (params['width']*1) || 630; //defaults to 630 if no paramaters were added to URL
		TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
		ajaxContentW = TB_WIDTH;
		ajaxContentH = TB_HEIGHT - 45;
		if(imageGroup.indexOf('TB_iframe') != -1){// either iframe or ajax window	
				if(imageGroup.indexOf('change_border') !=-1)
				{
					ajaxTitle='<p style="font-weight:bold; padding-left:100px; padding-top:2px">THÔNG BÁO KHÁCH HÀNG VỀ CHẤT LƯỢNG VÀ ĐỘ AN TOÀN CỦA SỮA MEIJI</p>';
					$("#TB_window").css({'border':'1px solid #ffa5d0'});
				}
				urlNoQuery = imageGroup.split('TB_');
				$("#TB_iframeContent").remove();					
				if(params['modal'] != "true"){//iframe no modal				
					$("#TB_window").append("<div id='TB_title'><div id='TB_logo'><img src='images/meijilogo.png' alt='Meiji' border='0' title='Meiji' style='float:left' />"+ajaxTitle+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close' style='float:right;'><img src='" +BASE_URL+ "Views/zenko/images/cross.png' border=0 /></a></div><div style='clear:both;height:1px'><!----></div></div><iframe scrolling='auto' frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");			
				if(imageGroup.indexOf('change_border') !=-1) $("#TB_title").css({'backgroundColor':'#ffdded'});
				}else{//iframe modal
				$("#TB_overlay").unbind();
					$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>".show());
				}
				$("#TB_closeWindowButton").click(tb_remove);
			
				if(imageGroup.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(imageGroup.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
		}		
		else
		{		
		TB_WIDTH = 350;
		TB_HEIGHT = 140;
		tb_showIframe();
		tb_position();
		// End of iframe.
		if(0 === 0){//code to show html
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;		
			//var warningContent = "<img src='" +http_root+ "Views/zenko/images/info_icon.png' height='65' hspace='5' style='margin-right:5px;' vspace='5' align='left' border='0' />Xin lưu ý đây chỉ là thông tin tham khảo dành cho cán bộ y tế. Vui lòng click xác nhận nếu là cán bộ y tế và có nhu cầu tìm hiểu thêm thông tin sản phẩm.";
			//var caption = 'Trước khi bạn tiếp tục...';
			/* Show title and content of warning*/
					if($("#TB_window").css("display") === "block"){						
						if(0 === 0){//ajax no modal
						$("#TB_window").append("<div id='TB_ajaxWindowTitle'>"+caption+"</div><img src='" +BASE_URL+ "Views/zenko/images/cross.png' onclick='tb_remove();' style='cursor:pointer;float:right;padding:10px;' vspace='0' hspace='0' border='0'/><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'>"+warningContent+"</div><div id='TB_closeAjaxWindow'><input type='button' value='Xác nhận' onclick='tb_go2NewWindow(\""+url+"\");' style='width:80px'/> <input type='button' value='Trở về'onclick='tb_remove();' style='width:80px'/></div>");					
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}			
//			$("#TB_closeWindowButton").click(tb_remove);
//			$("#TB_openWindowButton").click(tb_go2NewWindow);			
		}
	}
	document.onkeyup = function(e){   
		if (e == null) { // ie
				keycode = event.keyCode;
		} else { // mozilla
				keycode = e.which;
		}
		if(keycode == 27){ // close
				tb_remove();
		}  
	  };
		
	} catch(e) {
		//nothing here
	}
}

/********************************************************/
//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

/*Redirect to others page*/
function tb_go2NewWindow(url){
	document.location.href = url;
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

/*Remove all setting */
function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}
/*position view on x,y desktop */
function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}
/*verify type of brownser*/
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
