/*!
  IPA, common.js
  Copyright (C) 2009 Intercon e-consulting, http://www.intercon.pl
*/

var IPAApps = new function() {
	var self = this;
	var version = "1.2.1 :: 06/04/11";
	var inited = false;

	this.getVersion = function () {
		return version;
	};

	this.theme = '';

	this.Cnts = {
		'CAROUSEL'	: 'carouselWrapper',
		'LOGOS'		: {
					'cnt'	: 'trustedClients',
					'time'	: 4000,
					'speed'	: 800
				  },
		'GMAP'		: {
					'cnt'	: 'GMap',
					'zoom'	: 14,
					'lat'	: 52.2353467,
					'lng'	: 20.9824316,
					'icon'	: '/.templates/img/marker.gif',
					'title'	: 'IPA S.A. Oddział w Polsce'
				  },
		'COMBO_CLASS'	: 'linkedCombos',
		'PAGE_CONTENT'	: 'content'
	};

	this.showTab = function () {
		var sel = IC.util.History.getCurrentState("tabs");
		tc.selectedTab = sel;
		if (!_tabsPreloaded) {
			tc._changeSelected();
		} else {
			_tabsPreloaded = false;
		}
	};

	var initTabs = function () {
		try {
			tabbedContent.init('tabbedContent', 'tc', tabsArr);
			IC.util.History.register("tabs", tc.selectedTab.toString(), function() {IPAApps.showTab();});   
			IC.util.History.initialize("yui-history-field", "yui-history-iframe");
			IC.util.History.onReady(function () {
				IPAApps.showTab();
			});
		} catch (e) {}
	};

	var initCarousel = function() {
		if (elm = $('#' + IPAApps.Cnts['CAROUSEL'])[0]) {
			$('#' + IPAApps.Cnts['CAROUSEL'] + ' .carousel').jCarouselLite({
				btnNext: ".next",
				btnPrev: ".prev",
				visible: 6,
				circular: true
			});
			$('#' + IPAApps.Cnts['CAROUSEL'] + ' ul > li > a').prepend('<span>&nbsp;</span>');
		}
		if (elm = $('#' + IPAApps.Cnts['LOGOS']['cnt'])[0]) {
			$('#' + IPAApps.Cnts['LOGOS']['cnt'] + ' .carousel').jCarouselLite({
				visible: 1,
				circular: true,
				auto: IPAApps.Cnts['LOGOS']['time'],
				speed: IPAApps.Cnts['LOGOS']['speed']
			});
		}
	};

	var initGMap = function () {
		if (elm = $('#' + IPAApps.Cnts['GMAP']['cnt'])[0]) {
			var latlng = new google.maps.LatLng(IPAApps.Cnts['GMAP']['lat'], IPAApps.Cnts['GMAP']['lng']);
			var myOptions = {
				zoom: IPAApps.Cnts['GMAP']['zoom'],
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(elm, myOptions);
			var marker = new google.maps.Marker({
				position: latlng, 
				map: map, 
				icon: IPAApps.Cnts['GMAP']['icon'],
				title: IPAApps.Cnts['GMAP']['title']
			});
		}
	};

	var initCombos = function () {
		var f = $('.' + IPAApps.Cnts['COMBO_CLASS']);
		if (f[0]) {
			for (var i = 0; i < f.get().length; i++)
				if (f[i].nodeName == 'FORM' && !f[i].elements['send']) {
					f[i].elements['options'].onchange = function () {
						Utils.openAddress (this.form.options); void(0);
					};
				} else if (f[i].nodeName == 'SELECT') {
					f[i].onchange = function () {
						Utils.openAddress (this); void(0);
					};
				}
			f.bind("submit", function (event) {
				event.preventDefault();
				Utils.openAddress (this.options);
			});
		}
	};

	var initExpandables = function() {
		var elms = $('#' + IPAApps.Cnts['PAGE_CONTENT'] + ' .expandable');
		if (elms[0]) {
			elms.each(function() {
				var elm = this;
				$(this)
					.hide()
					.addClass('hidden');
				$(this).prev().children('a.expand')
					.bind('click', function(event) {
						event.preventDefault();
						var self = this;
						if (!self.orig)
							self.orig = $(this).text();
						$(self).text('zwiń');
						if (!elm.clicked) {
							elm.clicked = true;
							$(elm)
								.toggleClass('hidden')
								.slideToggle('fast', function() {
									this.clicked = false;
									if ($(this).hasClass('hidden')) {
										$(self).text(self.orig);
									}
								});
						}
					});
			});
		}
	};

	this.initScripts = function() {
		initExpandables();
	};	

	function initKonfigurator() {
		var pName = 'branza';
		var s = window.location.search;
		var p = [];
		if (s) {
			var v = s.split('&');
			for (var i = 0; i < v.length; i++) {
				if (v[i].indexOf(pName + '=') > -1) {
					p = v[i].split('=');
					break;
				}
			}
		}
		if (p.length > 1) {
			$('#' + p[1]).css('display', 'block');
		}
	}

	function init() {
		if (inited) return;

		inited = true;

		if (typeof _tabsPreloaded != "undefined") {
			initTabs();
		}

		if (self.theme == 'konfigurator') {
			initKonfigurator();
		}

		initCarousel();
		initGMap();
		initCombos();
		initExpandables();
	}

	$(document).ready(init);
};

var __Utils__ = function () {
	var w = window;
	var d = document;
	var n = navigator;
	var version = "1.5.0 :: 17/11/09";

	this.getVersion = function () {
		return version;
	};

	this.UA = new function () {
		var list = "(MSIE|Firefox|Chrome|Opera|Safari|Konqueror)";
		var strm = function (re) {
			var m = 0, x = n.userAgent.match (re);
			m = x && x.length > 1 ? x[1] : 0;
			return m;
		};
		var agent = strm (list);
		var strv = function () {
			var re = new RegExp();
			switch (agent) {
				case 'Safari' : re = "\\/(\\d+\\.\\d+)\\.\\d+\\s" + agent; break;
				default : re = agent + "[\\s|\\/](\\d+\\.\\d+)";
			}
			return strm (re);
		};
		var version = null;
		if (agent == 'Opera') {
			version = strm (/Version\/(\d+\.\d+)/);//Opera10+
		}
		this.browser = agent;
		this.version = version || strv ();
		this.IE = strm (/MSIE\s(\d+\.\d+)/);
	};

	this.getId = function (eid, doc) {
		var el = null;
		try {
			if (doc) {
				el = doc.getElementById (eid);
			} else {
				el = d.getElementById (eid);
			}
			return el;
		} catch (e) {}
		return false;
	};

	this.getClass = function (oElm, sTagName, sClassName) {
		var aElms = (sTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName (sTagName);
		var aReturnElms = [];
		sClassName = sClassName.replace (/-/g, "\-");
		var oRegExp = new RegExp("(^|\s)" + sClassName + "(\s|$)");
		var elm;
	
		for (var i = 0; i < aElms.length; i++) {
			elm = aElms[i];
			if (oRegExp.test (elm.className)) {
				aReturnElms.push (elm);
			}
		}
		return (aReturnElms);
	};

	this.blurAnchovis = function () {
		if(d.getElementsByTagName) {
			var a = d.getElementsByTagName("A");
			for(var i = 0; i < a.length; i++) {
				a[i].onfocus = function() {this.blur()};
			}
		}
	}

	this.addEvent = function (obj, fnc, act) {
		if(obj.addEventListener)
			obj.addEventListener(act, fnc, false);
		else if(obj.attachEvent)
			obj.attachEvent('on' + act, fnc);
		return false;
	};

	this.removeEvent = function (obj, fnc, act) {
		if(obj.removeEventListener)
			obj.removeEventListener(act, fnc, false);
		else if(obj.detachEvent)
			obj.detachEvent('on' + act, fnc);
		return false;
	};

	this.saveCookie = function (name, value, days, path) {
		var expires = '', cPath = '';
		if (typeof path == "undefined") {
			cPath = '/';
		} else {
			cPath = path;
		}
		if (days) {
			var date = new Date ();
			date.setTime (date.getTime () + (days * 86400000));
			var expires = '; expires=' + date.toGMTString ();
		}
		document.cookie = name +'='+ value + expires + ';' + (path != '' ? ' path=' + cPath : '');
	};

	this.readCookie = function (name) {
		var nameEq = name + '=';
		var ca = document.cookie.split (';');
		for (var i = 0; i < ca.length; i++) {
			var 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 null;
	};

	this.getWindowW = function () {
		var x;
		if (x = w.innerWidth) {}
		else if (d.documentElement && (x = d.documentElement.clientWidth)) {}
		else if (d.body && (x = d.body.clientWidth)) {}
		return x||0;
	};

	this.getWindowH = function () {
		var x;
		if (x = w.innerHeight) {}
		else if (d.documentElement && (x = d.documentElement.clientHeight)) {}
		else if (d.body && (x = d.body.clientHeight)) {}
		return x||0;
	};

	this.getScrollX = function () {
		var x;
	    if (d.body && (x = d.body.scrollLeft)) {}
		else if (d.documentElement && (x = d.documentElement.scrollLeft)) {}
		else if (x = w.pageXOffset) {}
		return x||0;
	};

	this.getScrollY = function () {
		var x;
	    if (d.body && (x = d.body.scrollTop)) {}
		else if (d.documentElement && (x = d.documentElement.scrollTop)) {}
		else if (x = w.pageYOffset) {}
		return x||0;
	};

	this.getStyle = function (x, styleProp) {
		if (d.defaultView && d.defaultView.getComputedStyle)
			return d.defaultView.getComputedStyle (x, null).getPropertyValue (styleProp);
		else if (x.currentStyle)
			return x.currentStyle[styleProp];
		return null;
	};
};

var Utils = new __Utils__();

__Utils__.prototype.openAddress = function (elm) {
	var w = elm.value.split("@:");
	if (w && w.length > 1) {
		if (w[0] == "s") {
			document.location = w[1];
		} else {
			window.open(w[1]);
		}
	}
	return false;
};

__Utils__.prototype.popupOpen = function (win, x, y, n, p) {
	if (!win) return false;
	var winName = n ? n : 'IPA';
	var params = p ? p : 'menubar=no,resizable=no,toolbar=no,status=no,location=no,menubar=no,personalbar=no,scrollbars=yes';
	var t = Math.round((Utils.getWindowY() - y) / 2);
	var l = Math.round((Utils.getWindowX() - x) / 2);
	var nw = window.open(win, winName, 'top=' + t + ',left=' + l + ',width=' + x + ',height=' + y + ',' + params);
	return false;
};

__Utils__.prototype.getWindowX = function () {
	this.getWindowW();
};

__Utils__.prototype.getWindowY = function () {
	this.getWindowH();
};

/*tooltip - v1.3 :: 04 Nov'08 @ pp :: tworzony w locie*/
__Utils__.prototype.tooltip=function(e,t,o,i){var d=document,l,w,h,k;if(!d.createElement)return;var a=e.target||event.srcElement;
if(a.nodeName!='a'&&a.nodeName!='div')a=a.parentNode;if(!o||!(l=d.getElementById(o))){l=d.createElement("div");l.id=o;
l.style.position='absolute';d.body.appendChild(l);k=d.createElement("div");if(d.all)k.style.position='absolute';
l.appendChild(k);}else{k=l.lastChild;}if(i){if(l.firstChild.nodeName!="IFRAME"){i=d.createElement("iframe");i.src='';
i.frameBorder='no';i.scrolling='no';l.insertBefore(i,k);}else{i=l.firstChild;}}else{if(l.firstChild.nodeName=="IFRAME")
l.removeChild(l.firstChild);}l.style.display='block';l.style.width='auto';k.innerHTML=t;if(l.offsetWidth>390)
l.style.width='400px';if(i){i.style.width=k.offsetWidth+'px';i.style.height=k.offsetHeight+'px';}
l.move=function(e){e=e||event;w=e.clientX+10;if(w+k.offsetWidth>getWindowW())w-=k.offsetWidth+20;h=e.clientY+10;
if(h+k.offsetHeight>getWindowH())h-=k.offsetHeight+20;l.style.left=w+getScrollX()+"px";l.style.top=h+getScrollY()+"px";};
l.hide=function(){l.style.display='none';l.style.visibility='hidden';};l.style.visibility='visible';if(a.onmousemove)return;
a.onclick=function(){this.blur();if(this.href)d.location=this.href;return false;};a.onmouseout=l.hide;a.onmousemove=l.move;}
function getScrollY(){var d=document,x;if(x=d.body.scrollTop)return x;else if(x=d.documentElement.scrollTop)return x;else if(x=window.pageYOffset)return x;else return 0;}
function getScrollX(){var d=document,x;if(x=d.body.scrollLeft)return x;else if(x=d.documentElement.scrollLeft)return x;else if(x=window.pageXOffset)return x;else return 0;}
function getWindowW(){var d=document,x;if(x=window.innerWidth)return x;else if(x=d.body.clientWidth)return x;else return 0;}
function getWindowH(){var d=document,x;if(x=window.innerHeight)return x;else if(x=d.body.clientHeight)return x;else return 0;}

/*flash content lite v2.4.1 (embed tag version) :: 19 Dec'08 @ pp :: uses DomContentLoaded check (supports tabs), DOM functions to create flash object*/
/*revision: v2.4.1 :: corrected function testPluginVer() to detect installed flash plugin*/
/*script uses onDomLoad functions to detect if DOM is loaded from SWFObject by Geoff Stearns, Michael Williams, and Bobby van der Sluis*/
__Utils__.prototype.createSWFObj=function(){var el=null,args=arguments[0],lnk='#',trg='_self',params={},attr={'classid':'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',
'codebase':'http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab','pluginspage':'http://www.macromedia.com/go/getflashplayer','type':'application/x-shockwave-flash'},ver=null,
d=document,n=navigator,w=window,ua={ie:/MSIE/.test(n.appVersion),wi:/win/.test(n.appVersion.toLowerCase()),wk:/webkit/.test(n.userAgent.toLowerCase())},domFnArr=[],script=null,timer=null,
bDom=w["__DOMContentLoaded__"],gif=null,requiredVersion=6;var onDomLoad=function(){if(!d.getElementById){return;}if(typeof bDom=="undefined"){bDom=w["__DOMContentLoaded__"]=true;
var s=d.createElement("span");try{var t=d.getElementsByTagName("body")[0].appendChild(s);t.parentNode.removeChild(t);}catch(e){bDom=w["__DOMContentLoaded__"]=false;}}handleArgs();if(!bDom){
if(ua.ie&&ua.wi){try{d.write("<scr"+"ipt id=__ieDOMLoaded__ defer=true src=//:></scr"+"ipt>");script=d.getElementById("__ieDOMLoaded__");if(script){script.onreadystatechange=function(){
if(this.readyState=="complete"){this.parentNode.removeChild(script);callDomFunc();}}}}catch(e){}}else if(ua.wk&&typeof d.readyState!="undefined"){timer=setInterval(function(){
if(/loaded|complete/.test(d.readyState)){callDomFunc();}},10);}else if(typeof d.addEventListener!="undefined"){d.addEventListener("DOMContentLoaded",callDomFunc,false);}else{addEvent(callDomFunc);}}}
();function callDomFunc(){w["__DOMContentLoaded__"]=bDom=true;if(timer){clearInterval(timer);timer=null;}var dl=domFnArr.length;for(var i=0;i<dl;i++){domFnArr[i]();}}function addDomEvent(fn){if(bDom){
fn();}else{domFnArr[domFnArr.length]=fn;}}function addEvent(fn){if(typeof w.addEventListener!="undefined"){w.addEventListener("load",fn,false);}else if(typeof d.addEventListener!="undefined"){
d.addEventListener("load",fn,false);}else if(typeof w.attachEvent!="undefined"){w.attachEvent("onload",fn);}else if(typeof w.onload=="function"){var fnOld=w.onload;w.onload=function(){fnOld();fn();};}
else{w.onload=fn;}}function testPluginVer(){ver=(x=w["__installedFlashPluginVer__"])?x:null;if(ver&&requiredVersion>ver){return false;}var flashVer=null;
if(typeof n.plugins!="undefined"&&typeof n.plugins["Shockwave Flash"]=="object"){var desc=n.plugins["Shockwave Flash"].description;flashVer=parseInt(desc.replace(/^.*\s+(\d+)\.?\d*\s+\S+$/,"$1"),10);}
else if(typeof w['ActiveXObject']!="undefined"){for(var i=10;i>5;i--){var actXObject="ShockwaveFlash.ShockwaveFlash."+i;try{if(new ActiveXObject(actXObject)){flashVer=i;break;}}catch(e){}}}
w["__installedFlashPluginVer__"]=ver=flashVer;return requiredVersion<=ver;}function handleArgs(){var len;for(a in args){switch(a){case 'params':addParams(args[a]);break;case 'cnt':el=args[a];
attr['id']=args[a];break;case 'requiredVersion':requiredVersion=args[a];break;default:this[a]=args[a];}}if(!w["__SWFContentObject__"]){w["__SWFContentObject__"]=[];}
len=w["__SWFContentObject__"].length;w["__SWFContentObject__"][len]={'v':requiredVersion,'el':el,'params':params,'attr':attr};addDomEvent(initSWFObj);}function addParams(p){var k,v;for(k in p){v=p[k];
switch(k){case 'name':attr['id']=v;break;case 'width':attr[k]=v;break;case 'height':attr[k]=v;break;case 'movie':setFileName(v);break;default:params[k]=v;}}}function toLC(s){if(isNaN(s))
return s.toLowerCase();return s;}function setFileName(fn){var mname=((i=fn.indexOf('.swf'))>0)?fn.substr(0,i):fn;params['movie']=attr['src']=mname+'.swf';}function initSWFObj(){var i,j,o,x,fObj;
for(j=0;j<w["__SWFContentObject__"].length;j++){fObj=w["__SWFContentObject__"][j];if(fObj.inited)continue;if(!(x=d.getElementById(fObj.el)))return;else{fObj.el=x;fObj.inited=true;
requiredVersion=fObj["v"];}if(testPluginVer()){if(ua.ie&&ua.wi){var html='<object';delete fObj.attr['type'];delete fObj.attr['src'];delete fObj.attr['pluginspage'];for(var i in fObj.attr){
html+=' '+i+'="'+fObj.attr[i]+'"';}html+='>';for(var i in fObj.params){html+='<param name="'+i+'" value="'+fObj.params[i]+'" />';}html+='</object>';fObj.el.outerHTML=html;}else{
delete fObj.attr['classid'];delete fObj.attr['codebase'];delete fObj.params['movie'];for(i in fObj.params){fObj.attr[i]=fObj.params[i];}o=createElm('embed',fObj.attr);
fObj.el.parentNode.replaceChild(o,fObj.el);}}else if(gif){o=createElm('a',{target:trg,href:lnk});var img=createElm('img',{src:gif,id:fObj.attr['id'],width:fObj.attr['width'],
height:fObj.attr['height'],border:'0'});o.appendChild(img);fObj.el.parentNode.replaceChild(o,fObj.el);}else{nodes=fObj.el.childNodes;for(var i in nodes){if(nodes[i].className=='alternativeContent'){
altNode=nodes[i];if(ua.ie&&ua.wi){fObj.el.innerHTML=altNode.innerHTML;}else{fObj.el.innerHTML="";fObj.el.appendChild(altNode);}}}}fObj=null;}return false;}function createElm(oName,oAttr){var i,
elm=d.createElement(oName);for(i in oAttr){elm.setAttribute(i,oAttr[i]);}return elm;}}
