// Popup class 

var previousImageUploadButton;
var previousSupplementalMenu;
var previousDeleteButton;
var currentSideBarItem;
var previousSideBarItem = null;
var authoring = false;

InlinePopup = Class.create();
InlinePopup.prototype = { 
    initialize: function(opts) {
        var el = opts.element;
        if (!$(el)) return false;
        this.elem = $(el);
        this.content_elem = this.elem.down().next();
        this._setEvents();
        if (opts.content) {
            this._setContent(opts.content);
        };
    },
    open: function() {
        new Effect.Appear(this.elem, { duration: 0.5 } );
    },
    close: function() {
        new Effect.Fade(this.elem, { duration: 0.5 } );
    },
    _setEvents: function() {
        var c = this.elem.getElementsBySelector('DIV.close A')[0];
        Event.observe(
            c, "click", 
            this.close.bindAsEventListener(this), false
        );
    },
    _setContent: function(content) {
        this.content_elem.innerHTML = content;
    }

}
// Bookmark popup class 
BookmarkWin = Class.create();
BookmarkWin.prototype = { 
    initialize: function(opts) {
        this.elem = $(opts.element);
        if (!this.elem) return false;
        var a = new InlinePopup({
            element: this.elem,
            content: this._setContent(opts.bookmark)
        });
        a.open();
    },
    _setContent: function(bookmark) {
       var result;
       result = "<p>Please copy and paste the following URL into your web"
              + " browser</p>"
              + "<input type='text' value='" + bookmark  +"'></input>";
        return result;
    }
}

// Send to friend class 
SendToFriend = Class.create();
SendToFriend.prototype = { 
    initialize: function() {
        this.elem = $('send_to_friend');
        if (!this.elem) return false;
        this._form_elem = $('send_to_friend_form');
        if (!this._form_elem) 
            throw new Error('SendToFriend.initialize(): cant find form');
        this._popup = new InlinePopup({
            element: this.elem
        });
        SendToFriend.initialized_obj = this;
    },
    _serialize: function() {
        return this._form_elem.serialize();
    },
    _submit: function() {
        new Ajax.Request("sendmail.php", {
            asynchronous: true,
            method:       'post',
            postBody:     this._serialize()
        });
        alert('Your email has been sent. Thanks.');
        this._popup.close();

    }
}
SendToFriend.click = function () {
    if (typeof SendToFriend.initialized_obj != 'undefined') 
        delete SendToFriend.initialized_obj;
    new SendToFriend();
    var io = SendToFriend.initialized_obj; 
    io._popup.open();
};
SendToFriend.submit = function () {
    if (typeof SendToFriend.initialized_obj == 'undefined') new SendToFriend();
    var io = SendToFriend.initialized_obj; 
    if(check_stf_Data()) {
        io._submit();
    }
};


//Archive class
Archive = Class.create();
Archive.prototype = {
    initialize: function() {
        this.elem = $('archives');
        if (!this.elem) {
            throw new Error('Archive.initialize(): Element with'
                +' ID archives not found');
        }
        this._shown = false;
        this.fx = this._handleClick.bindAsEventListener(this);
        this._show();
        Archive.initialized_object = this;
    },
    _show: function() {
        //Event.observe( $('container'), "click", this.fx, true);
        new Effect.Appear(this.elem, {
            duration: 0.3,
            afterFinish: function() {this._shown = true}.bind(this)
        });
        th = this;
        this.timeOut = setTimeout("th._hide()", 3000);
    },
    _hide: function() {
        //Event.stopObserving( $('container'), "click", this.fx, true);
        new Effect.Fade(this.elem, {
            duration: 0.3,
            afterFinish: function() {this._shown = false}.bind(this)
        });
        this._shown = false;
    },
    _handleClick: function(e) {
        var clickedOn = Event.element(e);
        var x = Event.pointerX(e);
        var y = Event.pointerY(e);
        if (!Position.within(this.elem, x, y)) this._hide();
    }
}
Archive.click = function () {
    if (!Archive.initialized_object) new Archive;
    var io = Archive.initialized_object;
    if (!io._shown) { io._show() }
    else { io._hide() }
}



// Supplemental class 
Supplemental = Class.create();
Supplemental.prototype = {
    initialize: function(supplementalMenuId) { 
        this.elem = $(supplementalMenuId);
        if (!this.elem) {
            throw new Error('Supplemental.initialize(): Element with'
                +' ID Supplementals not found');
        }
        this._shown = false;
        this.fx = this._handleClick.bindAsEventListener(this);
        this._show();
		
		if(!Supplemental.initialized_objects){
			Supplemental.initialized_objects = new Array();
		}

		Supplemental.initialized_objects[supplementalMenuId] = this;
    },
    _show: function() {
        //Event.observe( $('container'), "click", this.fx, true);
        new Effect.Appear(this.elem, { 
            duration: 0.3, 
            afterFinish: function() {this._shown = true}.bind(this)
        });
    },
    _hide: function() {
        //Event.stopObserving( $('container'), "click", this.fx, true);
        new Effect.Fade(this.elem, { 
            duration: 0.3, 
            afterFinish: function() {this._shown = false}.bind(this)
        });
        this._shown = false;
    },
    _handleClick: function(e) {
        var clickedOn = Event.element(e);  
        var x = Event.pointerX(e);  
        var y = Event.pointerY(e);  
        if (!Position.within(this.elem, x, y)) this._hide();
    }
}
Supplemental.click = function (supplementalMenuId) {
	var io;
	
    if (!Supplemental.initialized_objects || !Supplemental.initialized_objects[supplementalMenuId]){
		new Supplemental(supplementalMenuId);
	}
	
    
	if(previousSupplementalMenu && previousSupplementalMenu != supplementalMenuId){
		if(io = Supplemental.initialized_objects[previousSupplementalMenu]){
			io._hide();
		} 
	}

    io = Supplemental.initialized_objects[supplementalMenuId];
	
	if (!io._shown){ 
		io._show();
	}/*
    else{ 
		io._hide(); 
	}*/
}
Supplemental.destroyAll = function () {
	Supplemental.initialized_objects = null;
}




// Article Rating
ArticleRating = Class.create();
ArticleRating.prototype = { 
    initialize: function(article_id) {
        if (!article_id) 
            throw new Error('ArticleRating.initialize(): need article_id');
        var answers = $$('#article_rating_form INPUT');
        var ans = 0;
        for (x=0; x<answers.length; x++) {
            if (answers[x].checked == true) { ans = answers[x].value; break }
        }   
        this._artid = article_id;
        this._rating = ans;
        this._submit_vote();
    },
    _submit_vote: function() {
        var ans = this._rating;
        var i = document.createElement('iframe');
        i.style.display = 'none';
        i.name = 'rating_response';
        //console.log(this._artid + "\t" + this._rating);
        i.src = '/ezine/rate_article/'
              + '?article=' + encodeURIComponent(this._artid) 
              + '&rating=' + this._rating;
        $('content').appendChild(i);
        this._submit_vote_success();
    },
    _submit_vote_success: function() {
      var content = "<p>Thanks for voting!</p>";
      var a = new InlinePopup({
        element: $('rating_thankyou')
      });
      a.open();
    }
}

// Filters 
ArticleFilter = Class.create();
ArticleFilter.prototype = { 
    initialize: function() {
        this._filter = $('filters');
        this._shown = false;
        if (!this._filter) 
            throw new Error('ArticleFilter.initialize: no elem with ID filter');
        ArticleFilter.initialized_obj = this;
    },
    _show: function() {
        new Effect.Appear(this._filter, {duration: 0.5})
        this._shown = true;
    },
    _hide: function() {
        new Effect.Fade(this._filter, {duration: 0.5})
        this._shown = false;
    }
}
ArticleFilter.click = function () {
    if (!ArticleFilter.initialized_obj) new ArticleFilter;
    var io = ArticleFilter.initialized_obj;
    if (!io._shown) { io._show() }
    else { io._hide() }

	//Supplemental.destroyAll();
}

ArticleFilter.hideIt = function(){
    if (!ArticleFilter.initialized_obj) new ArticleFilter;
    var io = ArticleFilter.initialized_obj;
    io._hide();
}

// SidebarItem 
SidebarItem = Class.create();
SidebarItem.prototype = { 

    initialize: function(opts) {
        this._imgPath = '';            

        Object.extend(this, {
          _articleURL: opts.articleURL,
					_relatedContentURL: opts.relatedContentURL,
          _linkType: opts.linkType,
          _categories: opts.categories,
          _thumbURL: opts.thumbURL,
					_altTags: opts.altTags,
					//_imageHREF: opts.imageHREF,
					//_deleteButton: opts.deleteButton,
					_article: opts.article,
					_authoring: opts.authoring,
					_img_id_prefix: opts.img_id_prefix,
					_external_link: opts.external_link,
					_aggregate_type: opts.aggregate_type,
					//_currentSupplementalMenu: opts.currentSupplementalMenu,
					//_previousImageUploadButton: opts.previousImageUploadButton,
					//_currentImageUploadButton: opts.currentImageUploadButton,
					//_currentDeleteButton: opts.currentDeleteButton,
          _popup: opts.popup,
					_display_thumb: opts.display_thumb,
					_selected: opts.selected,
          _title: opts.title,
					_rawUrl: opts.rawUrl,
          _desc: opts.desc
        });
				
        delete opts; // keep code clean. don't access options 
                     // past the constructor
        this._createDOMobj();
				this._addClickEvent();
		
				this._addMouseEvents();
        SidebarItem.items.push({
            categories: this._categories,
            DOMobj: this._DOMobj
        });
    },
    _createDOMobj: function() {

        var result = document.createElement('li');
        var hasThumb = this._thumbURL ? true : false;
				var hasImageHREF = this._imageHREF ? true: false;
				var authoring = this._authoring

				if(this._aggregate_type == "resources"){
					result.className = "resources";
				}

				if(this._aggregate_type == "sitemap"){
					result.className = "state-of";
				}
				
		
				if(this._selected == "true"  && authoring == "true"){
					result.style.border = "solid thin";	
				}

		
				result.id = "item_" + this._article
        
				// Thumbnail
        if (hasThumb && this._display_thumb) {

          var left_img = document.createElement('div');
          left_img.className = 'left_img';
					left_img.id = 'left_img_' + this._article;
          var img = document.createElement('img');
          img.id = this._img_id_prefix + this._article;
          img.src =this._thumbURL;
          img.height = 54;
          img.width = 74;
					img.alt = this._altTags;

					if(authoring == "true"){
						if (this._aggregate_type == "") {
							// This is a completely crazy hack.  If an image is uploaded but it's somehow corrupted
							// we have to be able to display something for the user to click on anyway.  I added
							// a div to an href and then set the background to the thumbnail placeholder.  This get's
							// the inner div clickable without messing around with events.
							var link = document.createElement('a');
							var holder_div = document.createElement('div');
							
							holder_div.setAttribute('style', 'width: 85px; height: 54px; background: url(../images/author_it/thumbnail_placeholder.gif) top left no-repeat; ; ');
							link.setAttribute('onclick', 'return showUploadImageWindow(' + this._article + ', "thumbnail_asset"' + ', "74 x 54")');
							
							
							holder_div.appendChild(img);
							link.appendChild(holder_div);
							left_img.appendChild(link);
		
						}
					}
					else{
						try{
		        	left_img.appendChild(img);
						}
						catch(e)
						{
							// Safari 2 has a bug that will blow out the JS interpreter upon the appendChild call.
							// This has been fixed in S3 but is a known issue for S2.  Catching and then ignoring 
							// the exception will produce a sidbar without images.
						}
					}
		

//			if(hasImageHREF){
//				var button = document.createElement('div');
//				button.innerHTML = this._imageHREF;
//				left_img.appendChild(button);
//			}
//			
//			if(this._deleteButton){
//				var button = document.createElement('div');
//				button.innerHTML = this._deleteButton;
//				left_img.appendChild(button);
//			}
//
        }
        // Body
        var left_txt = document.createElement('div');
        left_txt.className = hasThumb ? 'left_txt' : 'full_txt';
				left_txt.id = 'left_txt_' + this._article;

        var title = document.createElement('h3');
        //title.appendChild(document.createTextNode(this._title));
        title.innerHTML = this._title;
        var body = document.createElement('span');
        body.innerHTML = this._desc;
        //body.appendChild(document.createTextNode(this._desc));
		
		    if (!this._display_thumb) {
					left_txt.style.width = "255px";
				}
		
        left_txt.appendChild(title);
        left_txt.appendChild(body);
	
	
				if (authoring == "true") {
					var load_article_div = document.createElement('div');
					var article_link = document.createElement('a');
					
					article_link.appendChild(document.createTextNode("<<<"));
					article_link.hostname = "localhost";
					article_link.setAttribute('onclick', "Request('contentSwap', '" + this._articleURL + "'); Request('sideContentSwap', '" + this._relatedContentURL + "');");
					
					load_article_div.id = "load_article_div_" + this._article;
					load_article_div.setAttribute('style', 'border: thin solid black; background-color: black; margin-top: 0px; margin-right: -37px; width: 20px; display: block; height: 15px; float: right; display: none;');
					load_article_div.appendChild(article_link);
					left_txt.appendChild(load_article_div);
				}
		



				if (this._linkType == 'external' && authoring == "true") {
					var external = document.createElement('span');
					external.innerHTML = this._external_link;
			    left_txt.appendChild(external);
				}

        // Assemble
        if (hasThumb && this._display_thumb) {
					result.appendChild(left_img);
				}
					
      	result.appendChild(left_txt);
      	this._DOMobj = result;
	
				if(this._selected == "true"){
					if (authoring == "true"){
						left_img.style.display = "block"
						left_txt.style.width = "150px";
				
					}
				
					currentSideBarItem = this;
					previousSideBarItem = currentSideBarItem;
				}

    },
    _addClickEvent: function() {
        var fx;
        var internal_link = function() {
        
				currentSideBarItem = this;
	
				if (this._authoring == "true"){
					var current_image = document.getElementById('left_img_' + currentSideBarItem._article);
					var current_text = document.getElementById('left_txt_' + currentSideBarItem._article);
					var current_load_article_div = document.getElementById('load_article_div_' + currentSideBarItem._article);

					if(previousSideBarItem != null){
						var element = document.getElementById("item_" + previousSideBarItem._article);
						var image = document.getElementById('left_img_' + previousSideBarItem._article);
						var text = document.getElementById('left_txt_' + previousSideBarItem._article);
						var load_article_div = document.getElementById('load_article_div_' + previousSideBarItem._article);
	

						if(load_article_div != null){
							load_article_div.style.display = "none";
						}
						
						if($('body1').hasClassName('internal')){
							if(image != null){
								image.style.display = "none";
							}
		
							if(text != null){
								text.style.width = "225px";
							}
						}
						
						
						if(element != null){
							element.style.border = "none";
						}
	
					}

					document.getElementById("item_" + currentSideBarItem._article).style.border = "solid thin";
					previousSideBarItem = currentSideBarItem;
					
					
					if (current_image != null) {
		  			current_image.style.display = "block";
		  		}
					
					current_load_article_div.style.display = "block";
					current_text.style.width = "150px";
					

				}
				else{
					
					// Only treat the entire LI as a button when not authoring.
					//Request('contentSwap', '' + this._articleURL);
					//Request('sideContentSwap', this._relatedContentURL);
					window.location.href = this._rawUrl;

				}

//				
//				if(document.getElementById(previousImageUploadButton)){
//					document.getElementById(previousImageUploadButton).style.display = "none";
//				}
//				
//				if(document.getElementById(this._currentImageUploadButton)){
//					document.getElementById(this._currentImageUploadButton).style.display = "block";
//				}
//				
//				if(document.getElementById(previousDeleteButton)){
//					document.getElementById(previousDeleteButton).style.display = "none";
//				}
//				
//				if(document.getElementById(this._currentDeleteButton)){
//					document.getElementById(this._currentDeleteButton).style.display = "block";
//				}
//				
//				previousImageUploadButton = this._currentImageUploadButton;
//				previousDeleteButton = this._currentDeleteButton;
//
//				Supplemental.click(this._currentSupplementalMenu);
//				previousSupplementalMenu = this._currentSupplementalMenu
//			}
//			
            return false;
        }
        var external_link = function() {
			currentSideBarItem = this;

			if (this._authoring == 'false'){
            	window.open(this._articleURL, '_blank', '', '');
			}
			else{
				Request('contentSwap', '' + this._articleURL );
				Request('sideContentSwap', this._relatedContentURL);
			}
            return false;
        }
        if (this._linkType == 'internal') {
            fx = internal_link;
        }
        else if (this._linkType == 'external') {
            fx = external_link;
        }
        else return false;
        Event.observe(this._DOMobj, 'click', fx.bindAsEventListener(this), true);
    },
    _addMouseEvents: function() {
        var over = function() {
            this._DOMobj.addClassName = 'over';
        }
        var out = function() {
					if(this._DOMobj.hasClassName('over')){
						this._DOMobj.removeClassName = 'over';
        	}
				}
        Event.observe(this._DOMobj, 'mouseover', over.bindAsEventListener(this), true);
        Event.observe(this._DOMobj, 'mouseout', out.bindAsEventListener(this), true);
    }

}
SidebarItem.items = new Array();
SidebarItem.get_items_by_category = function(category) {

    var result = new Array();
    // Show all
    if (category == 'view all content' || category == 'all') {
        for (var i = 0, l = SidebarItem.items.length; i < l; i++) {
            var item = SidebarItem.items[i];
            result.push(item.DOMobj);
        }
    }
    // Show category
    else {
        for (var i = 0, l = SidebarItem.items.length; i < l; i++) {
            var item = SidebarItem.items[i];
            for (var j = 0, m = item.categories.length; j < m; j++) {
                var c = item.categories[j];
                if (c == category)
                    result.push(item.DOMobj);
            }
        }
    }
    return result;
}

// Sidebar
Sidebar = Class.create();
Sidebar.prototype = { 

    initialize: function(opts) {
        this._shown = true;
        this._elem = $(opts.elem);
        this._category = 'features'; // default category
        this._authoring = opts.authoring;
        this._populate();
        Sidebar.initialized_object = this;
    },
    _hide: function() {
        Effect.BlindUp(this._elem, {duration: 0.5, queue: 'end', afterFinish: Sidebar._complete_update });
    },
    _show: function() {
        Effect.BlindDown(this._elem, {duration: 0.5, queue: 'end'});
    },
    _clear: function() {
        var o = this._elem;
        while(o.firstChild) o.removeChild(o.firstChild);
    },
    _populate: function(category) {
		
        if(!category) category = this._category;

		var ulElement = document.createElement('ul');
        var items = SidebarItem.get_items_by_category(category);
		
		ulElement.id = "articleList";
		
        for (var i = 0, l = items.length; i < l; ++i) {
		    ulElement.appendChild(items[i]);
        }

		this._elem.appendChild(ulElement);
		
		if(this._authoring == "true"){
			Sortable.create("articleList", {onUpdate:function(){new Ajax.Request('/author_it/order_articles', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("articleList")})}})
    	}
	}
}
Sidebar.update = function(category) {
    if (!category)
        throw new Error('Sidebar._populate(): must pass category');
    if (!Sidebar.initialized_object) new Sidebar;
    ArticleFilter.click();
    $('renameMe').innerHTML = category;
    var io = Sidebar.initialized_object;
    io._category = category;
    io._hide();
    // when hide() is done it calls _complete_update()
}
Sidebar.update_NoFilter = function(category) {
    if (!Sidebar.initialized_object) new Sidebar;
    var io = Sidebar.initialized_object;
    io._hide();
    // when hide() is done it calls _complete_update()
}
Sidebar.updateWithoutListUpdate = function(category) {
    if (!category)
        throw new Error('Sidebar._populate(): must pass category');
    if (!Sidebar.initialized_object) new Sidebar;
    var io = Sidebar.initialized_object;
    io._category = category;
    io._hide();
    // when hide() is done it calls _complete_update()
}
Sidebar._complete_update = function() {
    var io = Sidebar.initialized_object;
    io._clear();
    io._populate();
    io._show();
}

Sidebar._refresh_sidebar = function(){
	new Ajax.Updater('government_articles', '/author_it/set_filter?category=13', {asynchronous:true, evalScripts:true});
}

Sidebar.switchFilter = function(controller, element_id, category){
    var io = Sidebar.initialized_object;


	if(io != null){
		Effect.BlindUp(io._elem, {duration: 0.5, queue: 'end', afterFinish:function(){new Ajax.Updater(element_id, '/' + controller + '/set_filter?category=' + category, {asynchronous:true, evalScripts:true});} });
	}	
}

Sidebar.hideIt = function() {
    var io = Sidebar.initialized_object;
	Effect.BlindUp(io._elem, {duration: 0.2, queue: 'end'});
	return false;
    // when hide() is done it calls _complete_update()
}

// Poll 
Poll = Class.create();
Poll.prototype = { 
    initialize: function(opts) {
		this._article = opts.article;
		this._root = opts.root;
        this._form = $('poll_form');
        this._bars = $$('#poll_results DIV.bar');
        this._percents = $$('#poll_results DIV.perc');
        this._submitButton = $$('#poll_form INPUT.submit')[0];
    },
    _submit: function() {
        // grab selected answer
        var answers = $$('#poll_form INPUT');
        var ans = 0;
        for (x=0; x<answers.length; x++) {
            if (answers[x].checked == true) { ans = answers[x].value; break }
        }  
        if (ans == 0) alert('Please choose a valid option');

        // post to server 
        new Ajax.Request(this._root + "/poll_for_article?article="+this._article, {
            parameters : { i: 2, q: ans },
            onSuccess: function(t) { this._submit_success(t) }.bind(this)
        });
    },
    _submit_success: function(transport) {
        this._results = eval( '(' + transport.responseText + ')' );
        this._show_results();
    },
    _show_results: function() {
        var votes = new Array();
        var total_votes = 0;
        for (var r in this._results) {
            total_votes += this._results[r];
            votes.push(this._results[r]);
        }
        for (var i = 0; i < votes.length; ++i) {
            width_i = votes[i] * 350 / votes.max() + 'px';
            if (this._bars[i])
                this._bars[i].style.width = width_i;
            if (this._percents[i])
                this._percents[i].innerHTML = 
                    Math.round(votes[i] * 100 / total_votes) + '%';
        }
        //#this._form.parentNode.removeChild(this._form);
        this._form.style.display = 'none';
        $('poll_results').style.display = 'block';
    }
}
Poll.submit = function () {
    if (typeof Poll.initialized_obj == 'undefined') new Poll();
    var io = new Poll(); 
    io._submit();
}

function showHideQuickNav(show) {
	if ($('quicknav')) {
		(show) ? $('quicknav').show():$('quicknav').hide();
	} else {
		Event.observe(window, 'load', function() {
			(show) ? $('quicknav').show():$('quicknav').hide();
		});
	}
}
