/**
 *  Browser History
 */
 
var TabsControl = {
	tabs: {}	
};
TabsControl.setDefaultTab = function(name, default_tab_id) {
	TabsControl.tabs[name] = 1;
	var hashTabNo = TabsControl.getHashTabNo(name);
	if (hashTabNo == -1) {
		TabsControl.setTab(name, default_tab_id, true);
	} else {
		//TabsControl.tabs[name] = hashTabNo;
	}
};
TabsControl.setTabHash = function(tabHash, replace) {
	var pair = tabHash.substring(1).split("=");
	TabsControl.setTab(pair[0], pair[1], replace);
};
TabsControl.setTab = function(name, id, replace) {
	HashControl.setParam(name, id, replace);
};
TabsControl.getHashTabNo = function(name) {
	var value = HashControl.getParam(name, -1);
	var number = Number(value);
	return isNaN(number)
		? -1
		: number; 
};
TabsControl._setAssociatedStyle = function(el, styleEl, name) {
	var associatedColor = globalEnv["associatedColor_" + name];
	$(el).css(styleEl, "#" + associatedColor.replace("#", ""));
}

TabsControl._clearAssociatedStyle = function(el, styleEl) {
	$(el).css(styleEl, "");
}

TabsControl._selectTab = function(name, id) {
	var $header = $("#" + name + "_header_" + id);
	if ($header.size() == 0) {
		setTimeout(
				function()  {
					TabsControl.setTab(name,
							TabsControl.tabs[name],
							true);
				}
				, 100);
		return;
	}

	var $tab = $("#" + name + "_content_" + id);
	if (id == this.tabs[name]) {
		verticalTabsFix();
	}

	var $oldHeader = $("#" + name + "_header_" + TabsControl.tabs[name]);
	var $oldHeader_decoration = $oldHeader.parents(".tab_status").eq(0);
	$oldHeader_decoration.removeClass("active opened");
  TabsControl._clearAssociatedStyle($oldHeader_decoration, "borderLeftColor");
  TabsControl._clearAssociatedStyle($oldHeader_decoration.find('.tab_button').eq(0), "color");	
	var $oldTab = $("#" + name + "_content_" + TabsControl.tabs[name]);
	$oldTab.hide();

	var $header_decoration = $header.parents(".tab_status").eq(0);
	$header_decoration.addClass("active opened");
	TabsControl._setAssociatedStyle($header_decoration, "borderLeftColor", name);
	TabsControl._setAssociatedStyle($header_decoration.find('.tab_button').eq(0), "color", name);
	$tab.show();
	
	verticalTabsFix();
	TabsControl.tabs[name] = id;
	
	function verticalTabsFix() {
		if($tab.parents(".vertical_tabs").length > 0) {
			fn.syncVerticalTabsHeight.changeContentHeight($header);
		}
	}
	
};
TabsControl._onHashChange = function(hash) {
	for (var name in this.tabs) {
		if (this.tabs.hasOwnProperty(name)) {
			var tabNo = TabsControl.getHashTabNo(name);
			TabsControl._selectTab(name, tabNo);			
		}
	}
};

/* -------------------------------------------------------------------------- */

var HashControl = {
	hash: "",
	hashChangeListeners: [],
	inited: false,
	timeout: null
};
HashControl.setHash = function(hash, locationReplace) {
	locationReplace = locationReplace || false;
	if (locationReplace) {
		var href = document.location.href.replace(/#.*/, "");
		href += hash;
		document.location.replace(href);
	} else {
		document.location.hash = hash;
	}
	//setFavicon(); // [ff]Bug 519028 
};
HashControl.addHashChangeListener = function(func) {
	this.hashChangeListeners.push(func);
};
HashControl._timedUrlCheck = function() {
	var hash = document.location.hash;
	if (this.hash != hash) {
		for (var i=0; i < this.hashChangeListeners.length; i++) {
			this.hashChangeListeners[i].call(window, hash);
		}
		this.hash = hash;
	}
	if (this.inited) {
		this.timeout = setTimeout(function() { HashControl._timedUrlCheck(); }, 100);
	}
};
HashControl.init = function() {
	if (this.inited) {
		return;
	}
	this.inited = true;
	HashControl._timedUrlCheck();
};
HashControl.stop = function() {
	clearTimeout(this.timeout);
	this.inited = false;
};
HashControl.getParam = function(name, defaultValue) {
	var hashString = document.location.hash;
	if (hashString.length > 0) {
		hashString = hashString.substring(1);
	} else {
		return defaultValue;
	}
	var pairs = hashString.split("&");
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split("=");	
		if (pair[0] == name) {
			if (!pair[1]) {
				return defaultValue;
			}
			return pair[1];
		}		
	}
	return defaultValue;
};
HashControl.setParam = function(name, value, locationReplace) {
	var oldValue;
	var found = false;
	var pairs = [];
	var hashString = document.location.hash;
	if (hashString.length > 0) {
		hashString = hashString.substring(1);
	}
	if (hashString.length > 0) {
		pairs = hashString.split("&");	
	} 
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split("=");	
		if (pair[0] == name) {
			oldValue = pair[1];
			if (oldValue != value) {
				pairs[i] = name + "=" + value;
			}
			found = true; break;
		}		
	}
	if (!found) {
		pairs.push(name + (value !== undefined 
			? "=" + value
			: "")
		);
	}
	HashControl.setHash("#" + pairs.join("&"), locationReplace);
	return oldValue;
};

HashControl.getNonPairedHashElements = function() {
	var hashString = document.location.hash;
	var pairs = [];
	var found = [];
	if (hashString.length > 0) {
		hashString = hashString.substring(1);
	}
	if (hashString.length > 0) {
		pairs = hashString.split("&");	
	}
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split("=");	
		if (!pair[1]) {
			found.push(pair[0]);
		}
	}
	
	return found;
}

/* -------------------------------------------------------------------------- */

var IframeHashStore = {
	iframe: null,
	interval: null,
	hash: "",
	count: 0,
	inited: false
};
IframeHashStore.init = function(iframe) {
	if (this.inited) {
		return;
	}
	this.inited = true;	
	this.iframe = typeof iframe == "string"
		? document.getElementById(iframe)
		: iframe;
	if (this.iframe == null) {
		return;
	}
	IframeHashStore.storeHash(document.location.hash);
	HashControl.addHashChangeListener(function(hash) { IframeHashStore._onHashChange(hash); });
};
IframeHashStore._onHashChange = function(hash) {
	this.storeHash(hash);
};
IframeHashStore._intervalCheck = function() {
	if(!this.iframe.contentWindow || !this.iframe.contentWindow.document.body) {
		return;
	}
	var storedHash = this.iframe.contentWindow.document.getElementById("state").innerHTML.replace(/&amp;/g, "&");
	if (this.hash != storedHash) {
		this.hash = storedHash;	
		HashControl.setHash(storedHash);
	}
};
IframeHashStore.storeHash = function(hash) {
	if (hash == this.hash) {
		return;	
	}
	if(!this.iframe.contentWindow || !this.iframe.contentWindow.document.body) {
		setTimeout(function() { IframeHashStore.storeHash(hash); }, 10);
		return;
	}
	this.hash = hash;
	var doc = this.iframe.contentWindow.document;
	var html = '<html><body><div id="state">' + hash + '</div></body></html>';
	
	doc.open("text/html", this.count++ == 0 ? "replace" : undefined);
	doc.write(html)
	doc.close();
	if (this.interval == null) {
		this.interval = setInterval( function() { IframeHashStore._intervalCheck(); }, 100); 
	}
};

/* -------------------------------------------------------------------------- */

var LinkTargetLocator = {};
LinkTargetLocator.jumpToElement = function(el) {
	var $el = $("[id="+ el +"], [name="+ el +"]").eq(0);
	if($el.exists()) {
		if($el.parents(".tab_content").exists()) {
			TabsControl.setTabHash("#" + $el.parents(".tab_content").eq(0).attr("id").replace("_content_","="), true);
		}
		LinkTargetLocator._jumpToElement($el);
	}
}
LinkTargetLocator._jumpToElement = function(el) {
	var _el = el;
	setTimeout(function() {
			if(_el.offset() != null) {
				$("html,body").scrollTop(_el.offset().top);
			} else {
				LinkTargetLocator._jumpToElement(_el);
			}}, 100);
}
LinkTargetLocator._onLinkClick = function(hash) {
	LinkTargetLocator.jumpToElement(hash.replace("#",""));
};

LinkTargetLocator.onDocumentReady = function() {
	var result = HashControl.getNonPairedHashElements()[0];
	result && LinkTargetLocator.jumpToElement();
};

/* -------------------------------------------------------------------------- */

HashControl.addHashChangeListener(function(hash) { TabsControl._onHashChange(hash); });

$(document).ready(function() {
	$("A.tab_button").click(function(e) {
		TabsControl.setTabHash(this.href.substring(this.href.indexOf("#")));
		e.preventDefault();
		e.stopPropagation();
	})
	$("A").not(".tab_button").each(function(index, el) {
		var el_hashIndex = el.href.indexOf("#");
		var el_searchIndex = el.href.indexOf("?");
		var el_href_noHash = el_hashIndex > -1
			? el.href.substring(0, el_hashIndex)
			: el.href;
		var el_href_noSearch = el_searchIndex > -1
			? el_href_noHash.substring(0, el_searchIndex)
			: el_href_noHash;

		var location_searchIndex = document.location.href.indexOf("?");
		var location_noHash = document.location.href.replace(/#.*/, "");
		var location_noSearch = location_searchIndex > -1
			? location_noHash.substring(0, location_searchIndex)
			: location_noHash;

		// roznica wylacznie o hash - wniosek - w linku jest sam hash	
		if (el_hashIndex > -1) {
			if (el_href_noHash == location_noHash) {
				var el_hash = el.href.substring(el_hashIndex);
				$(el).click(function(e) {
					if (el_hash.length > 4 && el_hash.substring(0, 4) == "#tab") {
						var pair = el_hash.substring(1).split("=");
						HashControl.setParam(pair[0], pair[1]);
					} else {
						LinkTargetLocator._onLinkClick(el_hash);
					}
					e.preventDefault();
					e.stopPropagation();
				})
				return;
			}
		}
		// roznica na poziomie search - hash nieistotny w porownaniu
		if (el_href_noSearch == location_noSearch && el_href_noHash != location_noHash) {
			$(el).click(function(e) {
				if(!$(this).hasClass('button_confirm')) {
					e.preventDefault();
	        e.stopPropagation();
	        if($(this).hasClass('new_window')) {
	          console.log('new window')
	          window.open(el_href_noHash + document.location.hash);
	        } else {
	          document.location = el_href_noHash + document.location.hash;
	        }
				}
			})
			return;
		}
	});
});




/*    ---    */

