/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006
Updated: Eric Hill
Date: 9 Jan 07

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

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

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

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

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
//addEvent(window, 'DOMContentLoaded', initialize);
//addEvent(window, 'DOMContentLoaded', getBrowserInfo);
Event.observe(window, 'unload', Event.unloadCache, false);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.content = ctrl.href;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		//only get the Browser Info if it hasn't been initialized
		if(browser == null)
			getBrowserInfo();
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('lightboxFixed').style.display=display;
	    	$('overlay').style.display = display;
	    	// This line is to close the lightbox if you click outside the modal window
	    	$('overlay').onclick =  this.deactivate.bindAsEventListener(this);
	
	    	$('lightbox').style.display = display;
	    	if(display != 'none') this.loadInfo();
	},


	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
		
	},
	
	// Display Ajax response
	processInfo: function(response){
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";	
		this.actions();			
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
	   link = Event.element(e);
	 //  link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));
	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	 
	},
	
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		Element.remove($('lbContent'));
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
	},

	loginAndComment: function() {
		var username = $F('modalUsername');
		var password = $F('modalPassword');

		if(username.length == 0 || password.length == 0) {
			alert("Username or password is not filled in.");
		} else {

			UserLogin.getUserLogin(username,password, {
			callback: function(data) {
				//process cookie
				if(data == true) {
					Cookie.set('IFWUSER', username, 2000, '/');
					//hide form
					Effect.SwitchOff('content');
					Effect.SwitchOff('notLoggedIn');
					$('ifwuser').innerHTML = "<a href='/account/account.html'>"+username+"</a>";
					Form.reset('loginForm');
					Effect.Appear('loggedIn', {duration: .5});
					
					//do this after check to see if a comment is there, if it is, submit it
					var comments = document.getElementById('commentsField');
					if(comments != null && comments.value.length > 0)
						submitComment();

					//once this is done, then

					//this.deactivate;
					deactivateHack();

				} else {
					//send to  page with error message
					alert("Incorrect username or password");
				}
			},
			errorHandler: function(message) {
				alert(message);
			}}
			);
		}
	},
	
	forgotPassword: function() {
		//this function isn't needed anymore
		var comments = "";
		if($("commentsField") == null)
			comments = "";
		else
			comments = formatComments($("commentsField").value);

		window.location="/account/login.html?returnUrl="+url;
	},
	registerUser: function(){
		try {
		if(validate() == true) {
			var comments = "";
			if($("commentsField") == null)
				comments = "";
			else
				comments = $("commentsField").value;
			UserLogin.insertProfileAndComment($F('signupUsername'), $F('signupEmail'), $F('signupPassword'), $F('challenge'), comments, url, {
				callback: function(data) {
		
					//after a successful insert, log the user in, and set their cookie
					Cookie.set('IFWUSER', $F('signupUsername'), 2000, '/');
					window.location="/account/addProfileInfo.html?status=Success&newEmail="+$F('signupEmail')+"&username="+$F('signupUsername')+"&returnUrl="+url;
				},
				errorHandler:function(message) {
					//if there an error
					//window.location="/account/signup.html?errorMsg="+message;
					if(message == "DUPLICATE_USERNAME")
                                                alert("We're sorry.  That Username is already in use on this site.  Please register using another username, or Login to access InfoWorld.com");
                                        else if(message == "DUPLICATE_EMAIL")
                                                alert("We're sorry.  That E-mail is already in use on this site.  Please register using another E-mail, or Login to access InfoWorld.com");
                                        else
                                                alert(message);
				}
			});
		} 
		} catch (e) {
			alert(e);
		}

	},
	
	reportAbuse: function() {
		var comment = document.getElementById("commentToDestroy");
		if(comment != null) {
		  	var commentId = comment.innerHTML;
			var id = commentId.match(/^id=(.*)$/);
			ArticleComments.flagComment(id[1], {
				callback: function(data) {
					alert("This comment has been reported");
					deactivateHack();
				},
				errorHandler:function(message){
					alert(message);
				}
			});
		}
	},	

	sendToLogin: function() {
		var comments = "";
		if($("commentsField") == null)
			comments = "";
		else
			comments = formatComments($("commentsField").value);
		window.location="/account/login.html?returnUrl="+window.location.pathname+"&comments="+comments;
	}
	
		
	
	
	
	
	
}

//strip out html tags, do not want to support that. as well as escaping any other characters
function formatComments(comments) {
	var formattedComments = new String(comments).stripScripts().stripTags().escapeHTML();
	formattedComments = escape(formattedComments);
	return formattedComments;

}
function validate() {
	var emailFilter = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	var usernameFilter = /^\w{4,}$/;

	if(!usernameFilter.test($F('signupUsername')))
		throw ("Username must be 4 characters minimum and can only contain characters and numbers");
	else if($F('signupEmail').length == 0)
		throw ("Please provide an email");
	else if(!emailFilter.test($F('signupEmail')))
		throw ("Please provide a valid email address");
	else if($F('signupPassword').length < 6 || $F('confirmSignupPassword').length < 6)
		throw ("Passwords need to be greater than 6 characters");
	else if($F('signupPassword') != $F('confirmSignupPassword'))
		throw ("The passwords entered do not match");
	else if($('toc').checked == false)
		throw ("Registration on InfoWorld.com requires you accept our Terms and Services");
	else
		return true;

}

function deactivateHack() {
			Element.remove($('lbContent'));
		
		if (browser == "Internet Explorer"){
			lightbox.prototype.setScroll(0,lightbox.prototype.yPos);
			lightbox.prototype.prepareIE("auto", "auto");
			lightbox.prototype.hideSelects("visible");
		}
		
		lightbox.prototype.displayLightbox("none");
}
/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];

	lightboxFixed = document.createElement('div');
	lightboxFixed.id='lightboxFixed';
	
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';

	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '<div id="lbLoadMessage">' +
						  '<center><table style="height:350px"><tr><td valign=middle><img src="http://www.infoworld.com/img/loading.gif"><br>Loading</td></tr></table>' +
						  '</div>';
	bod.appendChild(lightboxFixed);
	
	//bod.appendChild(overlay);
//	bod.appendChild(lb);
	lightboxFixed.appendChild(overlay);
	lightboxFixed.appendChild(lb);
}
/*
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	var newInnerHTML = bod.innerHTML + "<div id='overlay'></div><div id='lightbox' class='loading'><div id='lbLoadMessage'><center><table style=\"height:350px\"><tr><td valign=middle><img src=\"http://www.infoworld.com/img/loading.gif\"><br>Loading</td></tr></table></center></div></div>";
	alert(newInnerHTML);
	bod.innerHTML = newInnerHTML;

}
*/

