layoutManager = Class.create();
layoutManager.prototype={
	initialize : function() {
		this.expandedFrame = false;
        this.cloud_visible = true; //visibility flag for the tag cloud
		this.pageElements = {
			//'tag_group_header':'tag_group_header',
			'container':'container',
			'suggested':'suggested',
			'suggestedContainer':'suggestedContainer',
			'feedTabs':'feedTabs',
			'iframeHolder':'iframeHolder',
			'cloudButtons':'cloudButtons',
			'tagCloudLogo':'tagCloudLogo',
			'logo':'logo',
			'footer':'footer',
			'getMore':'getMore',
			'interest_label':'interest_label',
            'right-column-container' : 'right-column-container',
            'selected_tag': 'selected_tag'
			//'back':'back'
		};
		this.pageElements2 = {
                        'back':'back',
			'barlogo':'barlogo',			
			'bookmarkThis':'bookmarkThis',
			'dropDown':'dropDown',
			'separator1':'separator1',
			'separator2':'separator2',
			'separator3':'separator3',
			'separator4':'separator4',
			'sharethislabel':'sharethislabel',
			'currentTagHolderBlock':'currentTagHolderBlock',
			'nextPage':'nextPage',
			'prevPage':'prevPage',
			'sendToFriend2':'sendToFriend2',
			'tweet':'tweet',			
			'fbook':'fbook',
			'frame-breaker-wrapper': 'frame-breaker-wrapper'                      
		};
		this.shown = false;
		window.document.title = 'YourVersion - Discover Your Version of the Web\u2122';
	},
	/**
	 * Toggles between main discover page and the external viewer ("sliver") page
	 */
	toggle : function(url,title,itemID,urlID,term) {
		if (!this.shown) {
			layoutManager.scrollPosition = document.body.scrollTop;
			if(layoutManager.scrollPosition == 0){
				if (window.pageYOffset){
					layoutManager.scrollPosition = window.pageYOffset;
				} else {
					layoutManager.scrollPosition = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
				}
			}
			$('tag_group_header').hide();
                        if($('feedbackbutton')){
                            $('feedbackbutton').hide();
                        }
			this.hideAll(url, title);
			jQuery('html').css({ "overflow-y" : "hidden" });
			this.launchPage(url,title,itemID,urlID,term);
			//$('currentTageHolderBlock').hide();						
			$('tag_group_header').style.top='19px';//same parent tag container appears on both pages but has to be moved vertically
			$('tag_group_header').style.left='226px';//same parent tag container appears on both pages but has to be moved vertically			
			$('currentTagHolderBlock').style.top='15px';//ditto
			$('currentTagHolderBlock').style.left='226px';//ditto
			$('tag_group_header').show();
			$('cloudButtons').style.left='312px'; // making sure the cloud buttons shift around to account for IE layout of sliver buttons
			
			$(yourVersion.current_sliver_voting_widget_id).show();
			//$('currentTageHolderBlock').show();
			
            var breadcrumb_element = $('tag_group_header');
            if (breadcrumb_element.childElements().length > 1 || !$('AllId').hasClassName('sticky_open')) {
                //console.log('here1');
                breadcrumb_element.show();
            } else {
                //console.log('here2');                
                breadcrumb_element.hide();
            }
			this.shown = true;
		}else{
            this.collapseFrame(true);
			this.showAll();
                        if (!Prototype.Browser.IE || (Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) > 6) ) {
                            if($('feedbackbutton') != null)
                            	$('feedbackbutton').show();
                        }
			// if the selected term is outside the cloud (as a result of clicking a related term outside the cloud), show the breadcrumb item
			if (suggestedSites.term_outside_cloud) {
			  $('selected_tag').show();
			}
			jQuery('html').css({ "overflow-y" : "scroll" });
			//firstStory is used in launchPage to fix an IE 6 bug
			this.firstStory=false;
			$('tag_group_header').style.top='0';//same parent tag container appears on both pages but has to be moved vertically
			$('tag_group_header').style.left='0';//same parent tag container appears on both pages but has to be moved vertically			
			$('currentTagHolderBlock').style.top='0';//ditto
			$('currentTagHolderBlock').style.left='0';//ditto
			$('cloudButtons').style.left='412px'; // making sure the cloud buttons shift around to account for IE layout of sliver buttons
			$(yourVersion.current_sliver_voting_widget_id).hide();			
            
            var breadcrumb_element = $('tag_group_header');
            if (breadcrumb_element.childElements().length == 1 && $('AllId').hasClassName('sticky_open')) {
                //console.log('here3');                
                breadcrumb_element.hide();
        		jQuery('.tag_group_header').hide();
            } else {
        		jQuery('.tag_group_header').show();
            }
		    this.shown = false;
			// We run this line last because Safari terminates on this.myWindow in the hide() function.
            myBookmarkPopupManager.hide();
            window.scrollTo(0, layoutManager.scrollPosition);
            this.clip = undefined;
		}
//		this.shown = (this.shown)?false:true;
	},
	frameDetect : function() {
		if (this.frameDetection) {
			/*Dan commented this out
			var leave = confirm('Possible frame break detected from : '+this.currentPage.url+'. Do you really want to leave YourVersion.com?');
			 if (!leave) window.location = self.location;
			 */
			if (yourVersion.manual_frame_break == false) {
	    	yourVersion.logFrameBreak(suggestedSites.currentSliverItem); // log the framebreak
			  var leave = alert('To view that item, your browser is being redirected to '+this.parseURL(unescape(this.currentPage.url))+'.\n\nTo return to the YourVersion website, click the browser Back button.');
			}
		};
	},
	parseURL : function(url) {
    	result = url.match(/(https?:\/\/)([a-zA-Z0-9_\-\.]+)(:[0-9]+)?\/?(.*)?/);
   		host = result[2];
	    return host;
	},
	launchPage : function(url,title,itemID,urlID,term) {

	    // genes readability extractor
        // url = 'http://sircambridgeworks.com/readability.html?url='+encodeURIComponent(url);
		this.frameDetection = true;
		setTimeout(function() {this.frameDetection=false;}.bind(this),5000);
		if (document.getElementById('siteIframe')) {$('siteIframe').remove();};
		this.createHugeIframe(url);
		var displayTitle=title.gsub('&quot;', '\"');
	    displayTitle=displayTitle.gsub("&#039;", "'");
    	displayTitle=displayTitle.unescapeHTML();
		window.document.title='YourVersion - '+	displayTitle;
		
		this.currentPage = {url:encodeURIComponent(url),title:title,itemID:itemID,urlID:urlID,term:term,displayTitle:displayTitle};
		this.copyShortUrl();
		
		if ((typeof document.body.style.maxHeight == "undefined") && (this.firstStory != true)) {
			//this is Gene old's IE isolation code
			//this is a bug fix for IE6...the first time you go to the story page, it loads the iframe content but doesn't display it for some reason (although when you click the Next and Prev buttons, the iframe displays fine. so this code reloads the url again
			frames['bigIframe'].location.href=url;
			this.firstStory=true;
		};
		
		suggestedSites.currentSliverItem = itemID;
		
	    var suburl = ((url.length > 55)?url.escapeHTML().substr(0,52) + "...": url.escapeHTML());
	    var subtitle = ((displayTitle.length > 47)? displayTitle.escapeHTML().substr(0,44) + "...": displayTitle.escapeHTML());
		$('url').update('<span style="font-weight:bold; color:#333" title="' + displayTitle.escapeHTML() + '">' + subtitle + '</span><br /><span style="position: relative; z-index: 10;" title="'+ url.escapeHTML() +'">' + suburl +"</span>");
		
		// IframeMonitor.start();
		// this.currentNumber++;
		// Figure out verticle positioning using dhtmlHistory later
		// dhtmlHistory.add(term + "&" + item_id,1);
		dhtmlHistory.add(1,1);
	},
	copyShortUrl : function(){
		var short = decto(this.currentPage.urlID);
		if(typeof(this.clip) === "undefined" ){
			clip = this.clip = new ZeroClipboard.Client();
			clip.setCSSEffects( true );
			clip.setText(short);
			clip.addEventListener( 'load', function(client) {
				jQuery('#copyshorturl').css({"background":"transparent url('../images/copyshort.gif') no-repeat 0 0" });
			});
			clip.addEventListener( 'complete', function(client){
				var left_position = jQuery("#copyshorturl").position().left+13;
				var copied_note = jQuery("<div class=\"copiednote\" style=\"left:"+left_position+"px;\">copied short url to clipboard</div>");
				jQuery('#copyshorturl').after(copied_note);
				setTimeout(function(){
					copied_note.fadeOut("slow", function(){ copied_note.remove(); });
				}, 1500);
				window.document.title='YourVersion - '+	layoutManager.currentPage.displayTitle;
			});
			clip.glue('copyshorturl');
		} else {
			clip.setText(short);
		}
	},
	showAll : function() {
	  $(document.body).removeClassName("sliver");
    if($("sliver_breadcrumbs"))
      $("sliver_breadcrumbs").remove();
		//$(document.body).setStyle('background:#fff;height:auto;');
		//$H(this.pageElements).each(function(n){if (document.getElementById(n[0])) {$(n[0]).show();};});		
		//console.log(stateHandler.currentRenderer.cloud_visible);
		//account for tag cloud visibility state
	    // if (this.cloud_visible) {
	   //      stateHandler.currentRenderer.showTagCloud();
	   //  } else {
	   //      stateHandler.currentRenderer.hideTagCloud();
	   //  }       
	   //  if (layoutManager.cloud_visible) {
	   //    $('selected_tag').hide();
	   //  }   	
		if (document.getElementById('siteIframe')) {$('siteIframe').remove();};
		//$H(this.pageElements2).each(function(n){if (document.getElementById(n[0])) {$(n[0]).hide();};});
		window.document.title = 'YourVersion - Discover Your Version of the Web\u2122';
		//$('output_left').addClassName('clearLeft');
		// IframeMonitor.stop();
		$('tag_group_header').hide();

		this.shown = true;
	}, 
	hideAll : function(url, title) {		
	  $(document.body).addClassName("sliver");
    if($("sliver_breadcrumbs"))
      $("sliver_breadcrumbs").remove();
    if($("url")){
    	$("url").remove();
    }
    var displayTitle=title.gsub('&quot;', '\"');
    displayTitle=displayTitle.gsub("&#039;", "'");
	displayTitle=displayTitle.unescapeHTML();
    var suburl = ((url.length > 55)?url.unescapeHTML().substr(0,52) + "...": url.unescapeHTML());
    var subtitle = ((displayTitle.length > 47)? displayTitle.substr(0,44) + "...": displayTitle);
    var urlgroup = '<div id="url" style="font-size:8pt; position:relative; z-index:45; max-width:338px; overflow:hidden; white-space:nowrap;"><span style="font-weight:bold; color:#333" title="' + displayTitle.escapeHTML() + '">' + subtitle + '</span><br /><span style="position: relative; z-index: 10;" title="'+ url.escapeHTML() +'">' + suburl +"</span></div>";
    new Insertion.Bottom("leftside", urlgroup);
    var taggrp = $("currentTagHolderBlock").innerHTML=='All'?"":"<div class='tag_group_header'>" + $("tag_group_header").innerHTML + "</div>";
    var selected_tag = ($("currentTagHolderBlock").innerHTML.length > 13)?$("currentTagHolderBlock").innerHTML.substr(0,10) + "..." : $("currentTagHolderBlock").innerHTML;
    new Insertion.Bottom("rightside", "<div id='sliver_breadcrumbs' style=\"float:right; margin-right:5px;\">" + taggrp + "<div id='selected_tag' style=\"cursor:pointer; z-index:45;\ title=\""+ $("currentTagHolderBlock").innerHTML + "\" onclick=\"layoutManager.toggle();\">" + selected_tag + "</div></div>");

	$('tag_group_header').hide();
	jQuery('.tag_group_header').hide();
		//$(document.body).setStyle('background:url("tageditor/bar_bg4.png");background-repeat:repeat-x;height:40px;');
		//$H(this.pageElements).each(function(n){if (document.getElementById(n[0])) {$(n[0]).hide();};});
		//$H(this.pageElements2).each(function(n){if (document.getElementById(n[0])) {$(n[0]).show();};});
	},
	createHugeIframe : function(url) {
		var Width = '100%';
		var Height = (Prototype.Browser.Opera || Prototype.Browser.Chrome)?window.innerHeight-43:document.viewport.getDimensions().height-43;
		// var Height = '100%';
		// var style = 'margin:0;padding:0;border:0;position:relative;top:-19px';
		var style='';
		var whiteBg = Builder.node('div',{id:'siteIframe',style:'width:100%;position:absolute;padding-top:40px;left:0;top:0;'},[]);
		whiteBg.appendChild(this.constructIframe(Width,Height,url,'bigIframe','vertical',style));
		// whiteBg.appendChild(Builder.node('div',{id:'',style:'clear:both;'},[]));
		document.body.appendChild(whiteBg);
		Event.observe(window, 'resize', function() {
    		var Height = (Prototype.Browser.Opera || Prototype.Browser.Chrome)?window.innerHeight-43:document.viewport.getDimensions().height-43;
			if (document.getElementById('bigIframe') != null) {
				$('bigIframe').height = Height;
			}
		});
	},
	fixScrollPosition : function() {
		var height = document.viewport.getDimensions().height-65;
		if (this.shown) {
			$('test').setStyle({height:height});
		};		
	},
	constructIframe : function(width,height,url,name,scrolling,style){
					//draw the iframe and return the DOM node
					var iframe = document.createElement('iframe');
						iframe.setAttribute('id',name);
						iframe.setAttribute('allowtransparency','false');
						iframe.setAttribute('name',name+Math.random());
						//iframe.setAttribute('name',name);						
						// iframe.setAttribute('src','');
						iframe.setAttribute('src',url);
						// iframe.setAttribute('baseURI',url);
						iframe.setAttribute('FRAMEBORDER',0);
						iframe.setAttribute('style',style);
						iframe.setAttribute('width',width);
						iframe.setAttribute('height',height);
					if(scrolling == 'yes'){iframe.setAttribute('scrolling','yes');}
					else if(scrolling == 'vertical'){iframe.setAttribute('scrolling','vertical');}
					else{iframe.setAttribute('scrolling','no');}
					return iframe;	
                 },
  /**
   * Marks a story for removal from the 
   */ 
  done_with : function(item_id, thumbs_down) {
        if(thumbs_down === true){
        	jQuery('#i' + item_id).css({ "background-color" : "#f1b9b9"});
        } else {
        	jQuery('#i' + item_id).css({ "background-color" : "#DDE"});
        }
		addmehidden = jQuery('#i' + item_id).fadeOut("normal", function(){
			horizontalhidden = $('i' + item_id).previous('tr').remove();
			horizontalhidden.setStyle({ display: "", visibility: 'hidden' });
			addmehidden = $('i' + item_id).remove();
			addmehidden.setStyle({ display: "", visibility: 'hidden' });
			$('content').down('tbody').appendChild(addmehidden);
			$('content').down('tbody').appendChild(horizontalhidden);

			layoutManager.ajaxGetNewItem(item_id, 0);
			new Ajax.Request('index.php?l=markasdone&item_id=' + item_id, {
				method: 'post', asynchronous: true, 
				onComplete: function(a){ 	}
			});
		});

  },
  
  ajaxGetNewItem : function(item_id, attempt){
  	if (attempt < 3) {
		one_more_url = suggestedSites.lastAjaxUrlWithParams + "&onemore="+ attempt;
		new Ajax.Request(one_more_url, {
			method: 'get',
			asynchronous: true,
			onComplete: function(a){
				response = a.responseText;
				pattern = new RegExp(/No results were found/);
				if(pattern.test(response)){
					$('i' + item_id).previous('tr').remove();
					$('i' + item_id).setStyle({visibility:"visible"});
					jQuery('#i' + item_id).html("<td colspan=\"3\"><br />Congratulations, you have finished with all the items for this combination of interest and channel.<br />  To see more items, please click a different interest or channel, add a new interest, or try again in a few minutes to see new results.<br /></td>");
				}
				newitem = layoutManager.processNewItem(response);
				if (document.getElementById(newitem.id)) {
					layoutManager.ajaxGetNewItem(item_id, ++attempt);
				}
				else {
					layoutManager.addItem(newitem, item_id);
				}
			}
		});
	} else { // This may happen if there are no items remaining.
		layoutManager.removeWhiteSpace(item_id);
	}
  },
  
  processNewItem : function(item){
	var el = $_(item);
	var getting = el.find('tr');
	$_(getting[1]).hide();
	return getting[1];
  },
  
  addItem : function(newitem, item_id){
	insertionpoint = $('content').down('tbody');
	horizontal = $('i' + item_id).next('tr').remove();
	horizontal.setStyle({visibility:'hidden'});
	insertionpoint.appendChild(newitem);
	insertionpoint.appendChild(horizontal);
	jQuery(newitem).fadeIn();
	horizontal.setStyle({visibility:'visible'});
	$(newitem).show();
	suggestedSites.makeLinksLaunchTabs();
	yourVersion.setupThumbs();
	$('i' + item_id).remove();
  },
  
  removeWhiteSpace : function(item_id){
  	$('i' + item_id).next('tr').remove();
	$('i' + item_id).remove();
  },
  toggleFrame: function(){
	  if(this.frameExpanded === true){
		  this.collapseFrame();
	  } else {
		  this.expandFrame();
	  }
  },
  expandFrame: function(){
	  	  this.frameExpanded = true;
		  jQuery('#sliver').css({ height : '80px', backgroundColor: "#ddd" });
		  jQuery('#siteIframe').animate({ top : '80px', paddingTop: "0px" }, { complete: function(){
			  var removeIframe = ['<div id="hideIframe" style="font-size:8pt; display:block; position:relative; clear:both; margin:0 auto; width:990px; top:6px;">',
			  '<a id="backUp" title="Collapse" class="sliver-button sliver-rightside-button" style="margin-left:5px; top:0px;" onclick="layoutManager.collapseFrame();"></a>',
			  '<div style="display:inline-block; float:right;"><a href="' + $('frame-breaker').href + '" onclick="setCookie(\'noframe\', 1, 5000)">Always hide the YourVersion Toolbar</a></div>',
			  '<textarea id="fulladdress" rows="1" cols="400" scrolling="no" style="overflow:hidden; whitespace:pre-wrap; max-width:620px; height:60px; display:inline-block; font-size:8pt; float:left; border:0; background-color:transparent; font:inherit;" onclick="jQuery(this).select()" onkeypress="return false;">' + $('frame-breaker').href + '</textarea>',
			  '<div style="whitespace:pre-wrap; display:inline-block; float:left; margin-left:3px; "><a href="'+ $('frame-breaker').href + '">Go to this page</a></div>',
			  '</div>'].join('');
			  jQuery('#sliver').append(jQuery(removeIframe));
		  }});
  },
  
  collapseFrame: function(){
	  this.frameExpanded = false;
	  jQuery('#hideIframe').fadeOut().remove();
	  jQuery('#siteIframe').animate({ top : '0px', paddingTop: "40px" }, {complete: function(){
		  jQuery('#sliver').css({ height : '40px', backgroundColor: "transparent" });
	  }});
  },
  
  showDropArrow: function(){
	  jQuery('#dropDown').css({ visibility: 'visible' });
  },
  hideDropArrow: function(){
	  jQuery('#dropDown').css({ visibility: 'hidden' });
  }
};
layoutManager = new layoutManager();

bookmarkManager = Class.create({
	initialize: function(userID) {
		this.userID = userID;
		this.privateBookmark = 0;
		this.bookmarkTerms = "";
		//console.log('bookmarkManager instance created!');
	},
	bookmarkThis : function() {
		var someParams = {
			userID:this.userID,
			channelID: suggestedSites.currentTab,
			privateBookmark: this.privateBookmark,
			bookmarkTerms: this.bookmarkTerms,
			tagID:suggestedSites.termID
		};
		this.privateBookmark = 0;

		var bookmarkterms = "";
		var terms = this.bookmarkTerms;
		terms = terms.split(",");

		if(terms) {
		   for(var index = 0, l = terms.length; index < l; ++index) {
			  var thisterm = terms[index].strip();
			  bookmarkterms  = bookmarkterms + "<term>" + thisterm.escapeHTML() + "</term>";
		   }
		}

		layoutManager.currentPage.title = layoutManager.currentPage.title.escapeHTML();;
		var evalParams = Object.extend(someParams,layoutManager.currentPage);
		var xmlTemplate = new Template('<?xml version="1.0" encoding="utf-8"?>'+
	   '<envelope protocolVersion="1.2" recorderId="5d54151f-4afa-4243-8310-fbe9ca4a35bb" recorderVersion="1.2">'+
	   	'<bookmarkURL bind="1">'+
	   		'<url>#{url}</url>'+
			'<title>#{title}</title>'+
			'<userID>#{userID}</userID>'+
			'<tagID>#{tagID}</tagID>'+
			'<channelID>1</channelID>'+
			'<privateBookmark>#{privateBookmark}</privateBookmark>'+
			bookmarkterms +
	   		'</bookmarkURL>'+                                                                           '</envelope>');
			//alert(xmlTemplate.evaluate(evalParams));
		this.submitBookmark(xmlTemplate.evaluate(evalParams));
	},
	submitBookmark : function(xml) {
		var url = 'index.php?a=bookmarkurl';
		new Ajax.Request(url,{method: 'post',asynchronous :false,
			parameters : {ajax:xml},
			onComplete: function(a) {
			    if (a.responseText.match('error')) {
                    alert('An error occurred while trying to save your bookmark.\n If this continues, please contact customer support.');			        
			    }
		    }
		});
	}
});

IframeMonitor = Class.create({
	initialize : function(){
		// setInterval(this.checkSrc.bind(this),5000);
		this.currentSrc = '';
		this.newSrc = '';
	},
	start : function() {this.watching=true;this.watch();this.currentSrc = this.checkSrc();},
	stop  : function() {this.watching=false},
	watch : function() {
		if (this.watching==true) {
			var newSrc = this.checkSrc();
			if (this.currentSrc != newSrc) {
				//console.log('iframe source changed!!' + newSrc);
			};
			setTimeout(this.watch.bind(this),6000);
		};		
	},
	checkSrc : function() {
		if (document.getElementById('bigIframe')) {
			//console.log($('bigIframe').contentDocument.location.href);
			return $('bigIframe').contentDocument.location.href;
		}else{return 'huh';}
	}
});
// IframeMonitor = new IframeMonitor();

function onUnLoad(){
	alert('unloading!');
};

friendsManager2 = Class.create({
	initialize: function() {
	},
	sendToFriend : function() {
		var url = 'index.php?u=sharepage&'+Object.toQueryString(layoutManager.currentPage);
		window.open(url,'sharepopup', 'toolbar=no,width=510,height=560,screenX=20,screenY=20,scrollbars=no,status=no,titlebar=no,toolbar=no,menubar=no,directories=no,resizable=yes');
	}
});
friendsManager2 = new friendsManager2();
