(function() {

	plbe = function(el) { return document.getElementById(el); };
	
	plb = function() { return window.PraizedLightBox; };

	plbae = function(element, type, handler) {
		if (document.addEventListener)
			element.addEventListener(type, handler, false); // Other
		else
			element.attachEvent('on' + type, handler); // MSIE
	};
	
	plbet = function(event) {
		if (event.srcElement)
			return event.srcElement; // MSIE
		return event.target; // Other
	};
	
	window.PraizedLightBox = {
		
		_loggedIn   : false,
		
		_ieHackId   : 'plb_searchlet_ie_hack',
		_screenId   : 'plb_searchlet_screen',
		_wrapId     : 'plb_searchlet_wrap',
		
		iframeId    : 'plb_searchlet_iframe',
		
		_triggerUrl : false,
		
		_intervalId : false,
		
		_loginLogoutLinkID : 'praized_login_logout_link',
		
		_ui : function() {
			if ( plbe(plb()._ieHackId) && plbe(plb()._ieHackId).style )
				return;
				
			gH = document.documentElement.scrollHeight;
			
			if ( document.body.currentStyle )
				gH = gH + 30;

			if ( window.innerHeight ) 
				cH = window.innerHeight;
			else
				cH = document.documentElement.offsetHeight;
			
			if ( gH > cH )
				realHeight = gH + 'px';
			else if (cH > 1000)
				realHeight = cH + 'px';
			else
				realHeight = '1000px';

			ieHackDiv = document.createElement('div');
			ieHackDiv.id = plb()._ieHackId;
			ieHackDiv.style.zIndex = 999996;
			ieHackDiv.style.position = 'absolute';
			ieHackDiv.style.width = '100%';
			ieHackDiv.style.textAlign = 'left';
			ieHackDiv.style.height = realHeight;
			ieHackDiv.style.top = 0;
			ieHackDiv.style.left = 0;
			ieHackDiv.style.display = 'none';
			document.body.appendChild(ieHackDiv);
			
			screenDiv = document.createElement('div');
			screenDiv.id = plb()._screenId;
			screenDiv.style.zIndex = 999997;
			screenDiv.style.position = 'absolute';
			screenDiv.style.width = '100%';
			screenDiv.style.textAlign = 'left';
			screenDiv.style.height = realHeight;
			screenDiv.style.backgroundColor = '#000';
			screenDiv.style.opacity = 0.8;
			screenDiv.style.filter = 'alpha(opacity=80)';
			ieHackDiv.appendChild(screenDiv);

			wrapDiv = document.createElement('div');
			wrapDiv.id = plb()._wrapId;
			wrapDiv.style.zIndex = 999998;
			wrapDiv.style.position = 'absolute';
			wrapDiv.style.width = '100%';
			wrapDiv.style.textAlign = 'left';
			wrapDiv.style.height = realHeight;
			plbae(wrapDiv, 'click', function(){ plb().hide(); });
			ieHackDiv.appendChild(wrapDiv);
			
			var iframeWidth = 800;
			var iframeHeight = 420;
			var iframeMarginTop = Math.round( ( cH - iframeHeight ) / 2 );
			var iframeMarginLeft = Math.round( ( ( (window.innerWidth) ? window.innerWidth : document.documentElement.offsetWidth ) - iframeWidth ) / 2 );
			
			/*
			 * Unfortunately, we have to use innerHTML, or MSIE does not submit forms to the iframe...
			 */
			var iframeMargin = iframeMarginTop+'px 0pt 0pt '+iframeMarginLeft+'px';
			wrapDiv.innerHTML = '<iframe id="'
								+ plb().iframeId
								+ '" name="'
								+ plb().iframeId
								+ '" style="border: 1px solid green; margin: '
								+ iframeMargin
								+ '; z-index: 999999; position: fixed; width: '
								+ iframeWidth
								+ 'px; height: '
								+ iframeHeight
								+ 'px; background:#666 url(http://static.praized.com/praized-com/images/preloaders/black-and-white/praized-logo-preloader-120x120-666666.gif) center center no-repeat"'
								+ ' frameborder="0" ALLOWTRANSPARENCY="true"'
								+'></iframe>';
		},
		
		_clearHashes: function(){
			var hash = top.location.hash.replace('#','');
			if( hash.match(/^praized\{/) )
				top.location.hash = '#';
		},
		
		_hashPipe : function() {
			var hash = top.location.hash.replace('#','')
			var tmp;
			if(/MSIE 6/i.test(navigator.userAgent)){
				loc = top.location.toString();
				hash = loc.replace(/^[^\#]+\#/,'')
			}
			if ( hash && ( tmp = hash.match(/^praized\{(.*)\}$/) ) ) {
				if ( ! tmp[1] )
					return;
				tmp = tmp[1].replace(/^\s*/, '').replace(/\s*$/, '');
				
				if ( tmp.match(/^redirect=/) ) {
					plb().hide();
					if ( plb()._intervalId ) {
						window.clearInterval(plb()._intervalId);
						plb()._intervalId = false;
					}
					
					var redirectUrl = unescape(tmp.replace('redirect=', ''));
					top.location.href = redirectUrl;
				} else if ( tmp == 'close' ) {
					plb().hide();
				}
			}	
		},
		
		_disableLoginLogoutLinks : function() {
			/* if it exists, disable the login/logout button to avoid double clicks */
			if ( plbe( plb()._loginLogoutLinkID ) )
				plbe(plb()._loginLogoutLinkID).href = '#';
		},
			
		toggle : function(el, display) {
			if ( plbe(el) && plbe(el).style )
				plbe(el).style.display = display;
		},
		
		show : function(url) {
			if ( plb()._loggedIn == true )
				return;
			plb()._clearHashes();
			if ( ! plb()._intervalId )
				plb()._intervalId = window.setInterval(plb()._hashPipe, 100);
			plb()._ui();
			if ( url && url.match(plb()._triggerUrl) ) {
				if ( top.location.href.match(/^https/) && ! url.match(/^https/) )
					url.replace('http:', 'https:');
				plbe(plb().iframeId).src = url;
			}
			plb().toggle(plb()._ieHackId, 'block');
			/* plb()._disableLoginLogoutLinks(); */
		},
		
		hide : function() {
			if ( plb()._intervalId ) {
				window.clearInterval(plb()._intervalId);
				plb()._intervalId = false;
				parts = top.location.href.split('#');
				top.location.href = parts[0] + '#';					
			}
			if((f = document.getElementById(plb().iframeId)))
				f.src="about:blank";
			plb().toggle(plb()._ieHackId, 'none');
		},
		
		_urlModify : function(url) {
			 if ( url.match(/\?/) )
				 url += '&';
			 else
				 url += '?';
			 return url + 'i=signon';;
		},
		
		_linkScan : function(authServ) {
			if ( ! plb()._triggerUrl )
				return;
			
			var oAuthUrl = plb()._triggerUrl + '/oauth';
			
			var links = ( document.links )
					  ? document.links
					  : document.body.getElementsByTagName('a');
			
			if ( links && links.length && links.length > 0 ) {
				for ( key in links ) {
					link = links[key];
					if ( link.href && link.href.match(oAuthUrl) ) {
						link.id = plb()._loginLogoutLinkID;
						if ( plb()._loggedIn == true ) {
							link.href = 'javascript: plb().logout("'+link.href+'", "'+authServ+'"); void(0);';
						} else {
							link.href = plb()._urlModify(link.href);
							link.href = 'javascript: plb().show("'+link.href+'"); void(0);';
						}
					}
				}
			}
		},
		
		_formScan : function() {
			if ( ! plb()._triggerUrl )
				return;
			
			var merchantUrlPattern = new RegExp('^' + plb()._triggerUrl + '/merchants/[a-zA-Z0-9]{32,34}/[a-z]+');
			var userUrlPattern     = new RegExp('^' + plb()._triggerUrl + '/users/[a-zA-Z0-9_-]+/[a-z]+');
			var qaUrlPattern       = new RegExp('^' + plb()._triggerUrl + '/questions');
			
			var userUrlException   = new RegExp('^' + plb()._triggerUrl + '/users/(reset|forgot)_password');
			
			var forms = ( document.forms )
					  ? document.forms
					  : document.body.getElementsByTagName('form');
			
			if ( forms && forms.length && forms.length > 0 ) {
				for ( key in forms ) {
					form = forms[key];
					if ( form.action && ( form.action.match(merchantUrlPattern) || form.action.match(userUrlPattern) || form.action.match(qaUrlPattern) ) ) {
						if ( ! form.action.match(userUrlException) ) {
							form.action = plb()._urlModify(form.action);
							form.target = plb().iframeId;
							plbae(
								form,
								'submit',
								function(){
									plb().show();
									return true;
								}
							);
						}
					}
				}
			}
		},
		
		formSubmit : function(form_id) {
			if ( ! form_id || ! plbe(form_id) )
				return false;
			plb().show();
			plbe(form_id).submit();
			return true;
		},
		
		logout : function(url, authServ){
			if ( ! url.match(/^http/) )
				return;
			else if ( url.match(/\/$/) )
				url = url.replace(/\/$/,'');
			
			plb()._disableLoginLogoutLinks();
			
			if ( ! authServ.match(/^http/) )
				return;
			else if ( authServ.match(/\/$/) )
				authServ = authServ.replace(/\/$/,'');
			
			// Create the iframe to call praized's facebook logout
			var frame = document.createElement('iframe');
		
			var attributes = {
				src : authServ + "/logout?i=signon",
				name:"praized_logout_hidden_iframe",
				height: "1px",
				width:"1px",
				allowtransparency: 'true'
			};

			var styles = {
				position:'absolute',
				width:'600px',
				height:'300px',
				marginLeft: '-300px',
				background:'transparent',
				top:'10%',
				left:'50%',
				border:'0'
			}

			for(var k in attributes) frame.setAttribute(k, attributes[k]);

			for(var k in styles) frame.style[k] = styles[k];
		
			// Setup stuff for when the frame's finished loading
			var onFrameloaded = function(){
				// Give the user enough time to read the facebook popup;
				setTimeout(function(){
					window.location.href = url;
				}, 3000)
			}
				
			// onload event for every other browser
			if(undefined === frame.onreadystatechange){ 
				frame.onload = onFrameloaded;
			}else{ 
				// onload event for IE (works)
				frame.onreadystatechange = function(){
					if (/^(loaded|complete)$/.test(frame.readyState)) onFrameloaded();
				}
			}
			document.body.style.cursor = 'wait';

			document.body.appendChild(frame);
		},
		
		init : function(triggerUrl, loggedIn, authServ) {
			if ( ! triggerUrl.match(/^http/) )
				return;
			else if ( triggerUrl.match(/\/$/) )
				triggerUrl = triggerUrl.replace(/\/$/,'');
			
			if ( loggedIn != true )
				loggedIn = false;
			else
				plb()._loggedIn = true;
			
			if ( ! authServ.match(/^http/) )
				authServ = 'http://auth.praized.com';
			else if ( authServ.match(/\/$/) )
				authServ = authServ.replace(/\/$/,'');
				
			plb()._triggerUrl = triggerUrl;
			if ( loggedIn != true ) {
				plb()._hashPipe();
				plb()._formScan();
			}
			
			plb()._linkScan(authServ);
		}
	};

})();
