var win_pathToImage = "/js/loadingAnimation.gif";

$(document).ready(function(){
	ajaxwin_init('a.ajaxwin');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = win_pathToImage;
});

function ajaxwin_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || null;
	var a = this.href || this.alt;
	ajaxwin_show(t,a);
	this.blur();
	return false;
	});
}

function ajaxwin_show(caption, url) {

	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("ajaxwin_hideselect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='ajaxwin_hideselect'></iframe><div id='ajaxwin_overlay'></div><div id='ajaxwin_window'></div>");
				$("#ajaxwin_overlay").click(ajaxwin_remove);
			}
		}else{//all others
			if(document.getElementById("ajaxwin_overlay") === null){
				$("body").append('<div id="ajaxwin_overlay"></div><div id="ajaxwin_window"></div>');
				$("#ajaxwin_overlay").click(ajaxwin_remove);
			}
		}

		$("#ajaxwin_overlay").addClass("ajaxwin_overlayBG");//use background and opacity

		$("body").append("<div id='ajaxwin_shadow'></div>");

		if (caption===null) { caption = '&nbsp;'; }
        $("body").append("<div id='ajaxwin_load'><img src='"+imgLoader.src+"' /> Čekejte prosím...</div>");//add loader to the page
		$('#ajaxwin_load').show();//show loader


			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = ajaxwin_parseQuery( queryString ); // predane parametry

			TB_WIDTH = (params['width']*1) + 6 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 6;
			ajaxContentH = TB_HEIGHT - 25;
			
			if (url.indexOf('win_iframe') != -1){ // pouzijeme iframe okno
					urlNoQuery = url.split('win_');
                    if(params['modal'] == "true") { $("#ajaxwin_overlay").unbind(); }
					$("#ajaxwin_iframeContent").remove();

					$("#ajaxwin_window").append('<div id="ajaxwin_hd">' + caption + '</div>',
                                                '<div id="ajaxwin_winclose" title="Zavřít okno"></div>',
                                                '<iframe frameborder="0" hspace="0" src="'+urlNoQuery[0]+'" id="ajaxwin_iframeContent" name="ajaxwin_iframeContent'+Math.round(Math.random()*1000)+'" onload="ajaxwin_showIframe();" style="width:' + ajaxContentW + 'px;height:' + ajaxContentH + 'px;" ></iframe>');
			} else {// not an iframe, ajax
                if(params['modal'] == "true") { $("#ajaxwin_overlay").unbind(); }
			    if ($("#ajaxwin_window").css("display") != "block"){
                    $("#ajaxwin_window").append('<div id="ajaxwin_hd">' + caption + '</div>',
                                                '<div id="ajaxwin_winclose" title="Zavřít okno"></div>',
                                                '<div id="ajaxwin_content" style="width: ' + ajaxContentW + 'px; height: ' + ajaxContentH + 'px"></div>');
				} else{//this means the window is already up, we are just loading new content via ajax
				    $("#ajaxwin_content")[0].style.width = ajaxContentW +"px";
					$("#ajaxwin_content")[0].style.height = ajaxContentH +"px";
					$("#ajaxwin_content")[0].scrollTop = 0;
					$("#ajaxwin_hd").html(caption);
				}
			}

			$("#ajaxwin_winclose").click(ajaxwin_remove);

			if (url.indexOf('win_iframe') != -1){
					ajaxwin_position(); // vycentrujem okno
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#ajaxwin_load").remove();
						$("#ajaxwin_window").css({display:"block", position:"absolute"});
                        //$("#ajaxwin_window").easydrag();
					}
			} else {
					$("#ajaxwin_content").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						ajaxwin_position(); // vycentrujem okno
						$("#ajaxwin_load").remove();
						//ajaxwin_init("#ajaxwin_ajaxContent a.ajaxwin");
						$("#ajaxwin_window").css({display:"block", position:"absolute"});
                        //$("#ajaxwin_window").easydrag();
					});
			}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					ajaxwin_remove();
				}	
			};
		}

	} catch(e) {
		//nothing here
	}
}

function ajaxwin_showIframe(){
	$("#ajaxwin_load").remove();
	$("#ajaxwin_window").css({display:"block"});
}

function ajaxwin_remove() {
	$("#ajaxwin_winclose").unbind("click");
	$("#ajaxwin_load").remove();
	$("#ajaxwin_window").fadeOut("fast",function(){$('#ajaxwin_window,#ajaxwin_shadow,#ajaxwin_overlay,#ajaxwin_hideselect').trigger("unload").unbind().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;
}

function ajaxwin_position() {
    var pagesize = ajaxwin_getPageSize();
    $("#ajaxwin_window").css({left: parseInt((pagesize[0] - TB_WIDTH) / 2, 10) + 'px', width: TB_WIDTH + 'px', top: parseInt((pagesize[1] - TB_HEIGHT) / 2, 10) + 'px'});
    $("#ajaxwin_shadow").css({left: parseInt((pagesize[0] - (TB_WIDTH + 6)) / 2, 10) + 'px', width: (TB_WIDTH+2) + 'px', top: parseInt((pagesize[1] - (TB_HEIGHT + 6)) / 2, 10) + 'px', height: (TB_HEIGHT+11) + 'px'});
}

function ajaxwin_resize(newWidth, newHeight, centered) {
    var pagesize = ajaxwin_getPageSize();
    TB_WIDTH = newWidth;
    TB_HEIGHT = newHeight;
    if (centered) {
        $("#ajaxwin_window").css({left: parseInt((pagesize[0] - newWidth) / 2, 10) + 'px', top: parseInt((pagesize[1] - newHeight) / 2, 10) + 'px'});
        $("#ajaxwin_shadow").css({left: parseInt((pagesize[0] - (newWidth + 6)) / 2, 10) + 'px', top: parseInt((pagesize[1] - (newHeight + 6)) / 2, 10) + 'px'});
    }
    $("#ajaxwin_window").css({width: newWidth + 'px', height: newHeight + 'px'});
    $("#ajaxwin_shadow").css({width: (newWidth + 2) + 'px', height: (newHeight + 3) + 'px'});
    $("#ajaxwin_content").css({width: (newWidth - 6) + 'px', height: (newHeight - 34) + 'px'});
}

function ajaxwin_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;
}

function ajaxwin_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

(function($){

	// to track if the mouse button is pressed
	var isMouseDown    = false;

	// to track the current element being dragged
	var currentElement = null;

	// global position records
	var lastMouseX;
	var lastMouseY;
	var lastElemTop;
	var lastElemLeft;

	// track element dragStatus
	var dragStatus = {};

	// returns the mouse (cursor) current position
	$.getMousePosition = function(e){
		var posx = 0;
		var posy = 0;

		if (!e) var e = window.event;

		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) {
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
		}

		return { 'x': posx, 'y': posy };
	};

	// updates the position of the current element being dragged
	$.updatePosition = function(e) {
		var pos = $.getMousePosition(e);

		var spanX = (pos.x - lastMouseX);
		var spanY = (pos.y - lastMouseY);

        var newTop = (lastElemTop + spanY);
        var newLeft = (lastElemLeft + spanX);

        var pagesize = ajaxwin_getPageSize();

        if (newTop<0) newTop = 0;
        if (newLeft<0) newLeft = 0;

        if (newTop + TB_HEIGHT>pagesize[1]) newTop = pagesize[1] - TB_HEIGHT - 20;
        if (newLeft + TB_WIDTH>pagesize[0]) newLeft = pagesize[0] - TB_WIDTH - 20;

		$("#ajaxwin_window").css({ top: parseInt(newTop, 10) + 'px', left: parseInt(newLeft, 10) + 'px' });
        $("#ajaxwin_shadow").css({ top: parseInt(newTop - 3, 10) + 'px', left: parseInt(newLeft - 3, 10) + 'px' });
	};

	$(document).mousemove(function(e){
		if(isMouseDown && dragStatus['ajaxwin_window'] == 'on'){
			// update the position and call the registered function
			$.updatePosition(e);
			return false;
		}
	});

	$(document).mouseup(function(e){
		if(isMouseDown && dragStatus['ajaxwin_window'] == 'on'){
			isMouseDown = false;
			return false;
		}
	});

	$.fn.easydrag = function(allowBubbling){

		return this.each(function(){
			dragStatus['ajaxwin_window'] = "on";

			$("#ajaxwin_hd").css("cursor", "move");

			$(this).mousedown(function(e){

				$("#ajaxwin_window").css("position", "absolute");
                $("#ajaxwin_shadow").css("position", "absolute");
				$(this).css("z-index", "10000");
				isMouseDown    = true;
				currentElement = this;

				var pos    = $.getMousePosition(e);
				lastMouseX = pos.x;
				lastMouseY = pos.y;

				lastElemTop  = this.offsetTop;
				lastElemLeft = this.offsetLeft;

				$.updatePosition(e);

				return allowBubbling ? true : false;
			});
		});
	};

})(jQuery);
