/**
 * @author POP.webdev
 * @version 0.2
 * @lastmodified 3/24/2008
 * @classDescription Provides a pairing of list item "tabs" with content elements and allows switching between them.
 * @return {Object}	Returns a new instance of the class.
 * @projectDescription
 * 
 * Dependencies:
 * - prototype v1.6 or later.
 */
var TabSwitcher = Class.create({
	initialize: function(links, items, options) {
		this.options = Object.extend({
			initialTabIndex: 0,
			tabOnClassName: 'selected',
			tabOffClassName: null,
			bodyOnStyles: {top: '171px', left: '21px', position: 'absolute'},
			bodyOffStyles: {top: '-50001px', position: 'absolute'}
			
		}, options || {});	
		// get dom references for tab and "body" content elements
		this.links = $$(links);
		this.items = $$(items);
		if (this.items.length == 0 || this.links.length == 0) {return;}
		
		// attach event handlers
		this.links.invoke('observe', 'click', this._linkClick.bindAsEventListener(this));

		// show initial item
		this.setItem(this.links[this.options.initialTabIndex]);
	},
	
	_linkClick: function(e) {
		Event.stop(e);  // stop event
		var link = Event.findElement(e, 'a');
		this.setItem(link); // show item
	},

	setItem: function(elLnk) {
		// add/remove selected class on parent LI (tab elements)
		var tabOffClassName = this.options.tabOffClassName;
		var tabOnClassName = this.options.tabOnClassName;
		
		this.links.each(function(lnk){			
			if(elLnk === lnk) {
				lnk.addClassName(tabOnClassName);
				if(tabOffClassName != null){
					lnk.removeClassName(tabOffClassName);
				}
			} else {
				lnk.removeClassName(tabOnClassName);
				if(tabOffClassName != null){
					lnk.addClassName(tabOffClassName);
				}				
			}			
		});
		
		// show/hide items ("body" content elements)
		var attHref = elLnk.readAttribute("href").replace(/.*#+/, '');
		this.items.each(function(elBody){
			if(elBody.id == attHref){
				elBody.setStyle(this.options.bodyOnStyles);
			}
			else{
				elBody.setStyle(this.options.bodyOffStyles);
			}
		}.bind(this));
	}
});

var TabSwitcherNextPrev = Class.create(TabSwitcher,{
	initialize: function($super, links, items, options) {
		this.prevLink = $(options.prevLink);
		this.nextLink = $(options.nextLink);
		this.options = Object.extend({
			initialTabIndex: 0,
			tabOnClassName: 'selected',
			tabOffClassName: null,
			bodyOnStyles: {top: '171px', left: '21px', position: 'absolute'},
			bodyOffStyles: {top: '-999991px', position: 'absolute'}
		}, options || {});
		// get dom references for tab and "body" content elements
		this.links = $$(links);
		this.items = $$(items);
		if (this.items.length == 0 || this.links.length == 0) {return;}
		
		// attach event handlers
		this.links.invoke('observe', 'click', this._linkClick.bindAsEventListener(this));
		this.readQueryString();
		// show initial item
		this.setItem(this.links[this.options.initialTabIndex]);
		this.prevLink.observe('click', this.__clickPrev.bindAsEventListener(this));
		this.nextLink.observe('click', this.__clickNext.bindAsEventListener(this));
		if(this.options.initialTabIndex == 0) {
			this.prevLink.show();
		}
	},
	setItem: function($super, elLnk) {
		$super(elLnk);
		var tabIndex = this.links.indexOf(elLnk);
		var tabContent = this.items[tabIndex];
		this.currentIndex = tabIndex;
		this.btnCheck();
		document.fire('tab:opened', {'tabIndex' :tabIndex, tab: elLnk , content: tabContent});
	},
    __clickPrev:function(e) {
		e.stop();
		this.currentIndex--;
		this.setItem(this.links[this.currentIndex]);
		this.nextLink.show();
	},
	__clickNext:function(e) {
		e.stop();
		this.currentIndex++;
		this.setItem(this.links[this.currentIndex]);
		this.prevLink.show();
	},
	btnCheck:function(){
	if(this.currentIndex == 0) {
			this.prevLink.show();
		}
	if(this.currentIndex == this.links.length -1) {
		this.nextLink.show();
	}
	},
	readQueryString: function(){
		var originalDefaultOpenTab = this.options.initialTabIndex;
		this.options.initialTabIndex = window.location.search.toQueryParams()['open-tab'];
		if(typeof(this.items[this.options.initialTabIndex]) == "undefined"){
			this.options.initialTabIndex = originalDefaultOpenTab;
		}
	}
});

var interstitialOverlay = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			targetLinkSelector: 'a.target-link',
			cancelLinkSelector: 'a.cancel-link',
			parentContainer: 'parent-overlay'
		}, options || {});
		this._createOverlay();
		this._insertOverlay();
		this.elDiv.hide();
        $$(this.options.targetLinkSelector).invoke('observe', 'click', this.__openClick.bindAsEventListener(this));
        $$(this.options.cancelLinkSelector).invoke('observe', 'click', this.__closeOverlay.bindAsEventListener(this));
	},

	_createOverlay: function() {
		this.elDiv = new Element('div', {'id': this.options.parentContainer});
		var elDivChild = new Element('div', {'id': this.options.parentContainer+'-child'});
		var elUl = new Element('ul');
		var elContinue = new Element('li');
		elContinue.insert(new Element('a', {'class': 'continue'}).update('<span class="offscreen">Continue</span>'));
		var elCancel = new Element('li');
		elCancel.insert(new Element('a', {'class': 'cancel-link', 'href': '#'}).update('<span class="offscreen">Cancel</span>'));
		this.elDiv.insert(elDivChild);
		elDivChild.insert(elUl);
		elUl.insert(elContinue);
		elUl.insert(elCancel);
	},

	_insertOverlay: function() {
		$('overlay').insert({after: this.elDiv});
	},

	show: function() {
		var viewportHeight = $(document.body).getHeight() + 'px';
		var viewportWidth = document.viewport.getWidth();
		this.elDiv.show();
		$('overlay').setStyle({
			display: 'block',
			height: viewportHeight,
			width: '100%'
		});
		$(this.options.parentContainer).setStyle({
			left: (viewportWidth - $(this.options.parentContainer).getWidth()) / 2 +'px'
		});
		$('overlay').observe('click', this.__closeOverlay.bindAsEventListener(this)); 
	},

	hide: function() {
		$('overlay').hide();
		this.elDiv.hide();
	},

    __openClick: function(e) {
    	Event.stop(e);
		var elLink = Event.element(e);
		var siteURL = elLink.readAttribute('href');
		$(this.options.parentContainer).down('a.continue').setAttribute('href', siteURL);
		this.show();
	},
	
	__closeOverlay: function(e) {
		Event.stop(e);
		this.hide(e);
	}

});

var PopUps = Class.create({
	initialize: function (elPopups, hDefaultWinOptions) {
		// create a default options hash
		this.defaultOptions = $H({
			width: 600,
			height: 600,
			//windowPosition: 'center', //['top-left'|'top-center'|'top-right'|'center'|'bottom-left'|'bottom-center'|'bottom-right']
			//left:  #,					// DIY left position of the window
			//top:  #,					// DIY top position of the window
			hOffset: 0,					// Horizontal offset
			vOffset: 0,					// Vertical offset
			location: 'no',
			menubar: 'no',
			status: 'no',		
			toolbar: 'no',
			scrollbars: 'no',
			resizable: 'yes',
			fullscreen: 'no',			// Display the window in theater mode?
			channelmode: 'no',			// Display the browser in full-screen mode? (must also be in theater mode)
			titlebar: 'no',
			windowName: 'popup'
		}).update(hDefaultWinOptions);

		var linkEventHandle = this.__LinkClick.bindAsEventListener(this);
		var elementEventHandle = this.__ElementClick.bindAsEventListener(this);
	
		elPopups.each(function(el){
			el.observe('click', (el.nodeName == 'A') ? linkEventHandle : elementEventHandle);
		});

	},
    __LinkClick: function (e){
		var el = Event.findElement(e, 'a');
 		var url = el.readAttribute('href');
 		var instanceOptions;
 		if(el.readAttribute('rel')){
 			instanceOptions = $H(el.readAttribute('rel').evalJSON());
 		}
		e.preventDefault();
		
		this.openWindow(url, instanceOptions);
	},
	
	__ElementClick: function (e){
		var el = e.element();
		var params = el.readAttribute('_popup').evalJSON();
 		var url = el.readAttribute('_popup');
 		var instanceOptions;
 		if(params.winOptions){
 			instanceOptions = $H(params.winOptions);
 		}
		this.openWindow(params.url, instanceOptions);
	},	
	
	openWindow: function(url, instanceWinOptions){
		// Merge specific options hash set in the rel with default options
		var options = (instanceWinOptions) ? this.defaultOptions.merge($H(instanceWinOptions)) : this.defaultOptions.clone();
		
		// position the window if specified
		if(options.get('windowPosition')){
			var pos = options.unset('windowPosition');	
			var left, top;
			var availHeight = screen.availHeight, availWidth = screen.availWidth;
			var popupHeight = options.get('height'), popupWidth = options.get('width');
			var vOffset = options.get('vOffset'), hOffset = options.get('hOffset');
			switch(pos){
				case 'top-left': 
					top = 0 + vOffset;
					left = 0 + hOffset;
					break;
				case 'top-center': 
					top = 0 + vOffset;
					left = ((availWidth - popupWidth)/2) + hOffset;
					break;
                    case 'top-right': 
					top = 0 + vOffset;
					left = availWidth - (popupWidth + hOffset);
					break;
				case 'center': 
					top = ((availHeight - popupHeight)/2) + vOffset;
					left = ((availWidth - popupWidth)/2) + hOffset;
					break;
				case 'bottom-left': 
					top = availHeight - (popupHeight + vOffset);
					left = 0 + hOffset;
					break;
				case 'bottom-center': 
					top = availHeight - (popupHeight + vOffset);
					left = ((availWidth - popupWidth)/2) + hOffset;
					break;
				case 'bottom-right': 
					top = availHeight - (popupHeight + vOffset);
					left = availWidth - (popupWidth + hOffset);
					break;
			}
			options.set('top', top);
			options.set('left', left);
		}

		var win = window.open(url, escape(options.unset('windowName')), options.invoke('join', '=').join(','));
		if (window.focus) {
			win.focus()
		}
	}
});

document.observe('dom:loaded', function(){
	popUps = new PopUps($$('.newsletter-popup'), {windowName: 'defaultWindowName', windowPosition: 'center', height: '600', width: '600'});
});

function getValue(varname) {
    
    var url = varname;
    var qparts = url.split("?");

    if (qparts.length == 0) {
      return "";
    }
  
    var query = qparts[1];
    var vars = query.split("&");
    var value = "";

    for (i=0;i<vars.length;i++) {
        var parts = vars[i].split("=");
    }
  
    value = parts[1];
    return value;
  
}
