var vbNavigation = Class.create();

vbNavigation.prototype = {


	// initialize()
    	// Constructor runs on completion of the Page loading.     	//
    
    	initialize: function() {

    		this.activeQuestion = null;
    		this.questionCount = 0;
    		this.timeout = null;
    		this.animateSpeed = 0.1;
    		this.imgNum = 0;

		this.processQAs();
		this.findPopups();
		this.findCTARollovers();
		this.findSignin();

	},
	
    	findSignin: function() {
    	
    		if($('signin')) {
    		
    			this.activateSignin($('signin'))
    		
    		}    	
    	
    	},
    	
    	
    	activateSignin: function(element) {
    	
    		Event.observe(element,'click', this.storeSigninLocation.bindAsEventListener(this));
    		element.writeAttribute("onclick", "return false");

    	},
    	
    	storeSigninLocation: function() {

	
    		thisUrl = location.href;
    		this.deleteCookie('signinLocation');
    		this.setCookie('sigininLocation',thisUrl);
    		redirectUrl = $('signin').href;
    		window.location = redirectUrl;
    	
    	},
	

	findPopups: function() {
	
	var popupItems = $$('a[rel^=popup]');
	

		popupItems.each(function(s) {

			this.activatePopup(s);

		}.bind(this));


	
	},
	
	activatePopup: function(element) {
	
	popupAttr = this.extractPopupAttributes(element);
	popupUrl = element.href;
	popupId = element.id+"-popup";
                var onClickCode = element.readAttribute("onclick");

                Event.observe(element,'click', function(event){
                    try {
                        eval(onClickCode);
                    } catch(err) {
                        eval(onClickCode.replace(new RegExp("return\s+\w*;?"),""));
                    }
                });

	element.writeAttribute("onclick", "return false");
	Event.observe(element,'click', function(event){Event.stop(event);});
	Event.observe(element,'click', this.openPopup.bindAsEventListener(this, popupUrl, popupId, popupAttr));
	
	},
	
	extractPopupAttributes: function(id) {
	
			popupStr = $(id).rel;
			popupStrSpl = popupStr.split("[");
			popupStrSpl = popupStrSpl[1].split("]");
			popupAttr = popupStrSpl[0].split(",");
			
			return popupAttr;
	
	},

	closePopup: function() {

		if (this.NewWin && (! this.NewWin.closed)) {
    			this.NewWin.close ();
  		} else {
    			return false;
  		}

	},
	
	openPopup: function(e, url,WinName,attr) {

	   this.closePopup();

	   // Set defaults according to the old function's settings
	   var defaultParamObj = {
	      resizable:'yes',
	      toolbar:'no',
	      scrollbars:'yes',
	      menubar:'yes',
	      status:'yes'
	      }
	   var params = ",";

	   if(attr[2]) { // Checks to see if the fifth parameter exists

	      var obj    = attr[2];

	      for (var prop in obj) { //Loops through the values in the object

		 defaultParamObj[prop] = obj[prop];  // replace defaults as necessary
	      }
	   }


	   for (var defaultProp in defaultParamObj) {

	      params+= defaultProp +"=" + defaultParamObj[defaultProp] +","; //rewrites the object in the correct string format

	   }

	   params = params.substring(0,params.length-1); //remove the comma at the end of the string

	   var winl = (screen.width - attr[0]) / 2;
	   var wint = (screen.height - attr[1]) / 2;
	   winprops = 'height='+attr[1]+',width='+attr[0]+',top='+wint+',left='+winl+params;

	   this.NewWin = window.open(url,'popup',winprops);
	   this.NewWin.focus();
	  
	},

	findCTARollovers: function() {

		var ctaItems = $$('a[rev^=rollover]');
		
		if(ctaItems.length > 0) {
				
			ctaItems.each(function(s) {

				this.activateCTA(s);
				
			}.bind(this));
					
		}			
	
	
	},
	
	activateCTA: function(element) {
	
		imageSrc = element.down().src;
		
		imageOverUrl = this.extractCTARolloverUrl(element);
		this.preloadImage(imageOverUrl);
	
		Event.observe(element,'mouseover',this.mouseoverCTA.bindAsEventListener(this, element));
		Event.observe(element,'mouseout',this.mouseoutCTA.bindAsEventListener(this, element, imageSrc));
		
	},
	
	
	
	mouseoverCTA: function(e,id) {
	
			mouseoverUrl = this.extractCTARolloverUrl(id);
			id.down().src = mouseoverUrl;
	
	},
	
	mouseoutCTA: function(e,id,src) {
	
			id.down().src = src;	

	},
	
	extractCTARolloverUrl: function(id) {
	
			rolloverStr = id.rev;
			rolloverStrSpl = rolloverStr.split("[");
			rolloverStrSpl = rolloverStrSpl[1].split("]");
			return rolloverStrSpl[0];
	
	},
	
	extractRolloverUrl: function(id) {
	
			rolloverStr = $(id).down().rev;
			rolloverStrSpl = rolloverStr.split("[");
			rolloverStrSpl = rolloverStrSpl[1].split("]");
			return rolloverStrSpl[0];
	
	},	
	
	processQAs: function() {

		var questions = $$('#content .question, #popup-content .question');
		
		if(questions.length > 0) {
		
			questions.each(function(s) {
			
				this.questionCount++;
				this.hideQAs(s);
				this.idQAs(s);
				this.activateQAs(s);	
				
			}.bind(this));
			
		}
	
	},
	
	
	hideQAs: function(element) {
	
		element.next(1).setStyle({'display':'none'});

	},
	
	idQAs: function(element) {
	
	element.writeAttribute("id", "question"+this.questionCount);
	element.next(1).writeAttribute("id", "answer"+this.questionCount);
	
	},
	
	
	activateQAs: function(element) {
	
		Event.observe(element,'click',this.actionQA.bindAsEventListener(this, element));	
	
	
	},
	
	
	actionQA: function(e, element) {
		

		if (element.id != this.activeQuestion && this.activeQuestion) {
		
		$(this.activeQuestion).next(1).hide();
		$(this.activeQuestion).setStyle({'fontWeight':'bold'});
		$(this.activeQuestion).addClassName('question');
		$(this.activeQuestion).removeClassName('question-over');
		
		}
	
		if(element.next(1).visible()) {
		
			element.next(1).hide();
			element.setStyle({'fontWeight':'bold'});
			element.addClassName('question');
			element.removeClassName('question-over');
		
		} else {
	
			element.setStyle({'fontWeight':'bold'});
			element.next(1).show();
			element.addClassName('question-over');
			element.removeClassName('question');
		
		}
		
		this.activeQuestion = element.id;
	
	},
	
	
	setCookie: function(name,value) {

	/** 
	 *  Sets session cookie of (name,value)
	 */ 

		document.cookie = name +"="+ value +";path=/;"

	},

	deleteCookie: function(name) {

	/** 
	 *  Deletes session cookie of (name)
	 */ 

		document.cookie = name + '=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT;';

	},
	
	getCookieValueFromName: function(name) {

	/** 
	 *  Returns cookie value from cookie name
	 */ 
		var cookies = document.cookie.split(';');
		for(var i = 0; i < cookies.length; i++) {	
			var cookie = cookies[i].split("=");
			if(cookie[0].replace(" ", "") == name) {
				return cookie[1];    
			}
		}
	},

	readCookieValueFromName: function(name) {

	/** 
	 *  Returns true if cookie found
	 */ 
		var cookies = document.cookie.split(';');
		for(var i = 0; i < cookies.length; i++) {	
			var cookie = cookies[i].split("=");
			if(cookie[0].replace(" ", "") == name) {
				return true    
			}
		}
	},
	
	preloadImage: function(imgUrl) {
	
		imageNumber = "imgpl"+this.imgNum
	
		imageNumber = new Image();
		imageNumber.src = imgUrl;
	
		this.imgNum++;
	
	
	},


	// Social Bookmarking methods

	findShareLink: function() {


		if($('share-link')) {


			shareLink = $('share-link');
			this.activateShareLink(shareLink)
			this.writeShareElement();

		}


	},


	activateShareLink: function(element) {

		Event.observe(element,'mouseover', this.shareMouseOver.bindAsEventListener(this));
		Event.observe(element,'mouseout', this.shareMouseOut.bindAsEventListener(this));

	},

	shareMouseOver: function() {


		window.clearTimeout(this.shareTimeout)

		$("share-popup").show();

		Event.observe("share-popup",'mouseover',this.sharePopupMouseOver.bind(this));
		Event.observe("share-popup",'mouseout',this.sharePopupMouseOut.bind(this));


	},

	shareMouseOut: function() {

		window.clearTimeout(this.shareTimeout)
		this.shareTimeout = setTimeout(function() { $("share-popup").hide(); }, 1000 )

	},

	writeShareElement: function() {

		var pageUrl   = escape(document.location);
		var pageTitle = document.title;

		buttonPos = $("shareButton").positionedOffset();
		popPosTop = buttonPos[1] + 16
		popPosLeft = buttonPos[0] - 200 + $("shareButton").getWidth()

		var bodyElmt = $$('body')[0];

	   // Determine which browser we're in //

		var IE = document.all ? true : false;

		if (IE) {
		  bookmarkLink = "<a title='Add this page to your favourites' href='javascript:window.external.AddFavorite(\""+pageUrl+"\", \""+pageTitle+"\")'><img src='images/favourites.gif'>&nbsp;Favourites</a>";
		}else{
		  bookmarkLink = "<a title='Add this page to your bookmarks' href='javascript:window.sidebar.addPanel(\""+pageTitle+"\", \""+pageUrl+"\",\"\")'><img src='images/favourites.gif'>&nbsp;Bookmark</a>";
		}

	   // Create the content for the popup //

		sharePopupContent  = "<div class='shareColumn'><div>";
		sharePopupContent += "<a title='Post this page to Facebook' href='http://www.facebook.com/sharer.php?u="+pageUrl+"' target='_blank'><img src='images/facebook.gif'>&nbsp;Facebook</a><br />";
		sharePopupContent += "<a title='Post this page to Del.icio.us' href='http://del.icio.us/post?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/delicious.gif'>&nbsp;Delicious</a><br />";
		sharePopupContent += "<a title='Post this page to Digg' href='http://digg.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/digg.gif'>&nbsp;Digg</a>";
		sharePopupContent += "</div></div><div class='shareColumn'><div>";
		sharePopupContent += "<a title='Post this page to Reddit' href='http://reddit.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/reddit.gif'>&nbsp;Reddit</a><br />";
		sharePopupContent += "<a title='Post this page to Stumbleupon' href='http://www.stumbleupon.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/stumbleupon.gif'>&nbsp;StumbleUpon</a><br />";
		sharePopupContent += bookmarkLink+"</div></div>";


		var sharePopupContainerElmt = new Element('div', { 'id':'popup-message'}).update(sharePopupContent);
		var sharePopupElmt = new Element('div', { 'id':'share-popup'}).update(sharePopupContainerElmt).hide();
		sharePopupElmt.setStyle({'position':'absolute','top':popPosTop+'px','left':popPosLeft+'px'});

		new Element.insert(bodyElmt, {bottom:sharePopupElmt});

	},



	sharePopupMouseOver: function() {

		window.clearTimeout(this.shareTimeout);

	},


	sharePopupMouseOut: function() {

		window.clearTimeout(this.shareTimeout)
		this.shareTimeout = setTimeout(function() { $("share-popup").hide(); }, 1000 )


	},
	
	test: function() {
	
	alert("Hello");
	
	}
	
}

Event.observe(window, 'load', function () {

new vbNavigation();

});