/*
 * Set true for debugging purposes
 */
var debug = true;
var layersOS_spm_site = "http://edita.layers.com/";
var osidContextIndentifier = "";



/**
 * @namespace
 * Class LayerOSToolbar
 * 
 * Created on 23 June 2009
 *  
 */
function LayersOSToolbar(osidIdentifier){

	this._templates = new LayersOSTemplates();
	
	osidContextIndentifier = osidIdentifier;
	this._osidIdentifier = osidIdentifier;

	this._permalink = false;
	this.execute();
}

//Templates
LayersOSToolbar.prototype._templates;

//Edita
LayersOSToolbar.prototype._osidIdentifier;
LayersOSToolbar.prototype._alreadyRendered;

// Common
LayersOSToolbar.prototype._displayable;
LayersOSToolbar.prototype._mainFrame;
LayersOSToolbar.prototype._bgPage;
LayersOSToolbar.prototype._loadingGauge;
LayersOSToolbar.prototype._messageBoard;
LayersOSToolbar.prototype._bgPageURL;
LayersOSToolbar.prototype._permalink;
LayersOSToolbar.prototype._state;
LayersOSToolbar.prototype._windowHeight;


// Not logged
LayersOSToolbar.prototype._joinButton;
LayersOSToolbar.prototype._joinForm;
LayersOSToolbar.prototype._loginButton;
LayersOSToolbar.prototype._loginForm;
LayersOSToolbar.prototype._layersOverThisPageButton;
LayersOSToolbar.prototype._layersOverThisPageAccordion;


// Logged
LayersOSToolbar.prototype._identitiesAccordion;
LayersOSToolbar.prototype._identitiesButton
LayersOSToolbar.prototype._layerTitleButton;
LayersOSToolbar.prototype._layerTitleForm; 
LayersOSToolbar.prototype._newLayerButton;
LayersOSToolbar.prototype._shareButton;
LayersOSToolbar.prototype._infoButton;
LayersOSToolbar.prototype._infoBox;
LayersOSToolbar.prototype._emailButton;
LayersOSToolbar.prototype._emailForm;
LayersOSToolbar.prototype._commentButton;
LayersOSToolbar.prototype._commentsAccordion;
LayersOSToolbar.prototype._likeButton;
LayersOSToolbar.prototype._reportButton;
LayersOSToolbar.prototype._myFriendsLayersButton;
LayersOSToolbar.prototype._myFriendsLayersAccordion;
LayersOSToolbar.prototype._layersOverThisPageLoggedButton
LayersOSToolbar.prototype._layersOverThisPageLoggedAccordion;
LayersOSToolbar.prototype._notificationsButton;
LayersOSToolbar.prototype._helpButton;
LayersOSToolbar.prototype._applicationBar;



/*
 *
 */
LayersOSToolbar.prototype.insertToolbarPlaceholder = function(){
	var tmp = this._templates.toolbarPlaceholder();
	
	try{
	  this._bgPage = $('body');
	  this._bgPage.append(tmp);
	}catch(e){
	  console.error("83");
	  console.error(e);
	  alert(e);
	  try{
		this._bgPage = $('body');
  		this._bgPage.append(tmp);
	  }catch(e){
	    console.error("91");
	    alert(e);
	  }			
	}
}



/*
 * Pablo
 */
LayersOSToolbar.prototype.enableLoggedEvents = function(){
	
}


/*
 * Pablo
 */
LayersOSToolbar.prototype.enableNotLoggedEvents = function(){
	
}

/*
 * Decide language properties file
 */
LayersOSToolbar.prototype.getPropertiesFile = function() {
    // DeclaraciÑn de la variable que va a contener el lenguaje del navegador
    //var navigatorLanguage ;
    
    // En funci—n del nombre del navegador se recupera la propiedad de una forma distinta
	/*
    if ($.browser.msie){
		navigatorLanguage = navigator.userLanguage ;
	}else{		
		navigatorLanguage = navigator.language;
	}
	*/
	return "en-us.properties";
	
    // En funci—n del lenguaje del navegador
    /*
	switch(navigatorLanguage) {
		// Firefox
        case 'es-ES':
        	return 'es-es.properties' ;
         // Safari
        case 'es-es':
            return 'es-es.properties' ;
         // Explorer
        case 'es':
            return 'es-es.properties' ;
        // El navegador no es en espanyol
        case 'es-CA':
            return 'es-ca.properties';
        case 'es-ca':
            return 'es-ca.properties';
        case 'ca':
            return 'es-ca.properties';
        default:
            return 'en-us.properties' ;
    }
    */
}

/*
 * drawLogged
 */
LayersOSToolbar.prototype.drawLogged = function(){
  
  console.info("LayersOSToolbar.prototype.drawLogged");
  
  if (typeof(LayersOSToolbar.prototype._alreadyRendered) == "undefined" || LayersOSToolbar.prototype._alreadyRendered == false){
    console.info("LayersOSToolbar.prototype.drawLogged - 166");
  	try {
      try{
    		this._displayable = $('#layersOS_dock').empty();

    		var html = this._templates.loggedToolbarHTML();
    		$('#layersOS_dock').html(html);

    		// Delete this._identitiesAccordion object
    		this._identitiesAccordion = null;

    		var tmp = $('#layersOS_dock_mylayer_title');
    		this._layerTitleButton = new LayersOSTitleButton(this, tmp); // Defined in LayersOSButtons.js
    		this._layerTitleButton.disable();

    		var tmp = $('#layersOS_toolbar');
    		this._applicationBar = new LayersOSApplicationBar(this, tmp); // Defined in LayersOSApplicationBar.js
    		
    		var tmp = $('#layersOS_dock_add');
    		console.info("add new button +");
    		this._newLayerButton = new LayersOSNewLayerButton(this, tmp); // Defined in LayersOSButtons.js	
    		var tmp = $('#layersOS_dock_identities');
    		this._identitiesButton = new LayersOSIdentitiesButton(this, tmp); // Defined in LayersOSButtons.js
    		var tmp = $('#layersOS_dock_publish');
    		this._shareButton = new LayersOSPublishButton(this, tmp); // Defined in LayersOSButtons.js
    		this._shareButton.disable();

    		var tmp = $('#layersOS_dock_info_layer');
    		this._infoButton = new LayersOSInfoButton(this, tmp); // Defined in LayersOSButtons.js		

    		var tmp = $('#layersOS_dock_email');
    		this._emailButton = new LayersOSEmailButton(this, tmp); // Defined in LayersOSButtons.js	

    		var tmp = $('#layersOS_dock_comment');
    		this._commentButton = new LayersOSCommentButton(this, tmp); // Defined in LayersOSButtons.js

    		var tmp = $('#layersOS_dock_like');
    		this._likeButton = new LayersOSLikeButton(this, tmp); // Defined in LayersOSButtons.js	
    		var tmp = $('#layersOS_dock_report');
    		this._reportButton = new LayersOSReportButton(this, tmp); // Defined in LayersOSButtons.js		
    		var tmp = $('#layersOS_dock_layers_myfriends');
    		this._myFriendsLayersButton = new LayersOSMyFriendsLayersButton(this, tmp); // Defined in LayersOSButtons.js	
    		var tmp = $('#layersOS_dock_layers_over_page');
    		this._layersOverThisPageLoggedButton = new LayersOSLayersOverThisPageLoggedButton(this, tmp); // Defined in LayersOSButtons.js	
    		/*
    		var tmp = $('#layersOS_dock_notifications');
    		this._notificationsButton = new LayersOSNotificationsButton(this, tmp); // Defined in LayersOSButtons.js
    		this._notificationsButton.disable();
    		*/
    		var tmp = $('#layersOS_dock_install');
    		this._helpButton = new LayersOSHelpButton(this, tmp); // Defined in LayersOSButtons.js
    		this._helpButton.disable();

      }catch(e){
        console.error(e);
      }
  		//os.openLayer(os.getCurrentLayer());
  		try {
  			this.setTitleText(os.currentLayer._title);
  		}catch(e){
  			console.info('layer not loaded yet');
  		}

  		// Enable buttons depending on the way we entered the system
  		if (this._permalink) {
  			this._infoButton.enable();
  			this._emailButton.enable();
  			this._commentButton.enable();
  			this._likeButton.enable();
  			this._reportButton.enable();
  		}
  		else {
  			this._infoButton.disable();
  			this._emailButton.disable();
  			this._commentButton.disable();
  			this._likeButton.disable();
  			this._reportButton.disable();
  			this._layerTitleButton.enable();
  		}

  		// Set unload event to window to warn the user if he is in the middle of a layer creation. The way to check it is by checking if the share button is enabled.
  		window.onbeforeunload = function(event) {
  		    if( this.toolbar._shareButton._displayable.hasClass('.layersOS_dock_item_clickable') ) {	
  		        event.returnValue = STRING_save_before_unload;
  		    }
  		}

  	LayersOSToolbar.prototype._alreadyRendered = true;

  	}catch(e){
  		console.error(e);
  	}
  }

}


/*
 * drawNotLogged
 */
LayersOSToolbar.prototype.drawNotLogged = function(){
  console.info("LayersOSToolbar.prototype.drawNotLogged");
  console.info("alreadyLoaded->");
  console.info(LayersOSToolbar.prototype._alreadyRendered);
  console.info("<-alreadyLoaded");
  
  if (typeof(LayersOSToolbar.prototype._alreadyRendered) == "undefined" || LayersOSToolbar.prototype._alreadyRendered == false){
    console.info("LayersOSToolbar.prototype.drawNotLogged");

  	this._displayable = $('#layersOS_dock');
  	console.info("displayable");
  	console.info(this._displayable);

  	var html = this._templates.notLoggedToolbarHTML();
  	$('#layersOS_dock').html(html);

  	var tmp = $('#layersOS_dock_join');
  	this._joinButton = new LayersOSJoinButton(this, tmp); // Defined in LayersOSButtons.js

  	var tmp = $('#layersOS_dock_login');
  	this._loginButton = new LayersOSLoginButton(this, tmp); // Defined in LayersOSButtons.js

  	var tmp = $('#layersOS_dock_layers_over_page');
  	this._layersOverThisPageButton = new LayersOSLayersOverThisPageButton(this, tmp); // Defined in LayersOSButtons.js

    LayersOSToolbar.prototype._alreadyRendered = true;
    console.info("set alreadyLoaded->");
    console.info(LayersOSToolbar.prototype.drawNotLogged);
    console.info("<-set alreadyLoaded");
  	//os.openLayer(os.getCurrentLayer());  
  }
}



/*
 * 
 */
LayersOSToolbar.prototype.endLoadBgPage = function(){
	
	// We are loading a layer from layersOverThis list
	if (this._state == "openLayerFromList"){		
		os.openLayerAfterBGPLoad(os.getCurrentLayer());
		return true;
	}
	
	os.openLayerAfterBGPLoad(os.getCurrentLayer());
	
	//this._loadingGauge.hide();
	
	console.info('LayersOSToolbar.prototype.endLoadBgPage');
	
	//this.addWmodeToEmbeds();
	
	// Some websites, such as wired.com, remove the subdomain part from their document domain. In such a case, we set our document domain to layers.com to allow access to the background page.
	try{
		this._bgPage.contents()[0].domain;
	}catch(e){	
		document.domain = 'layers.com';
	}	
			
	// set iframe height equal as background page height
	try{
	  this._bgPage.height(this._windowHeight);		
	}catch(e){
	  console.error("292");
	  console.error(e);
	  alert(e);
	}
	
		
	//this.checkHeight();	
}

LayersOSToolbar.prototype.checkHeight = function(){
	
	var iframe_height = this._bgPage.contents().find('html')[0].scrollHeight;
	var iframe_body_height = this._bgPage.contents().find('body')[0].scrollHeight;				
			
	this._bgPage.height( Math.max(iframe_height, iframe_body_height) );
		
	setTimeout('os.toolbar.checkHeight()', 2000);
}

/*
 * Entering through permalink
 */
LayersOSToolbar.prototype.loadBgPage2 = function(){
	try{
		var me = this;
		this._permalink = true;
	
		var url1 = this._bgPage[0].src;
		var url2 = os.computeIframeSrc(os.currentLayer._siteURL);		
	
		os.openLayer(os.getCurrentLayer());	
		
		if( url1 != url2 ){
			this._bgPage[0].src = url2;
		
			os._bgUrl = os.currentLayer._siteURL;

//			this._bgPage.bind("load", function(){ try{ me.endLoadBgPage(); }catch(e){ console.error(e); throw(e);} } );
			me.endLoadBgPage();
		}else{
			me.endLoadBgPage();
		}
	}catch(e){
		console.error(e);
	}
}


/*
 * Loads the background page and sets its correct dimensions
 *
 */
LayersOSToolbar.prototype.loadBgPage = function(){
	
	try{
		os.currentLayer = new Layer();
		
		try{
			var user = os.checkLogin();
			
			if(user != undefined){
				this.drawLogged();
			}
		}catch(e){
			this.drawNotLogged();
		}
		
		// Save the window size  
		this._windowHeight = $(window).height();
		//this._bgPage = $('#backgroundPage');
		try{
		  this._bgPage = $('body');
		}catch(e){
	    console.error("354");
		  console.error(e);
		  alert(e);
		}
		
		
		// Set the backgroundPage iframe height to 1500px to allow most of the objects to accommodate
		/*
		try{
		  this._bgPage.height(1500);
		}catch(e){
		  	  console.error("364");
		  console.error(e);
		  alert(e);
		}
		*/
		
		os._bgUrl_is_layers = false;
		
		var me = this;
		
		//var tmp = os.getBGPageURL();
		
		var tmp = window.top.location.href;
		
		console.info("url->");
		console.info(tmp);
		console.info("<-url");  
    
		
		if(typeof(tmp) == undefined){
			console.info("no bgpage - permalink!");
		}else{
		  /*
		  try{
		    this._bgPage[0].src = tmp;
		  }catch(e){
		    	  console.error("382");
		    console.error(e);
		    alert(e);
		  }
			*/
			os._bgUrl = tmp;
			
			console.info("bgpage - go on");
			try{
			  //this._bgPage.bind("load", function(){ try{ me.endLoadBgPage(); }catch(e){throw(e);} } );
			  me.endLoadBgPage();
			}catch(e){
			  	  console.error("393");
			    console.error(e);
			    alert(e);
			}
			
		}
		
	}catch(e){
		console.error(e);
		throw(e);
	}
}


/*
 *
 */
LayersOSToolbar.prototype.loadLanguage = function(){
	var me = this;
	try{
		eval( os.importScript( "http://edita.layers.com/deploy/lang/lang.php", "langTags", function(){ try{ me.loadBgPage();}catch(e){throw(e);} } ) );
	}catch(e){
		throw(e);
	}
}


/*
 * main
 */
LayersOSToolbar.prototype.execute = function(){
  
  if(document.getElementById("layersOS") == null){
      
    	try{
    		os = new LayerOS(this);

    		if(typeof(this._osidIdentifier) == "undefined"){
    			this._osidIdentifier = osidContextIndentifier;
    		}

    		//this._mainFrame = $('#mainFrame');
    		this._mainFrame = $('#dashboard');
    		this._bgPage = $('#dashboard');

    		//this._loadingGauge = new LayersOSLoadingGauge(this);
    		//this._loadingGauge.show();

    		this.loadLanguage();
    		try{
    			//totalURL = jQuery.url.param("url");

    			this.insertToolbarPlaceholder();
    			os.setPopUpBoard( $('#layersOS_popupboard') );

    			var tmp = $('#layersOS_log_messages');
    			this._messageBoard = new LayersOSMessageBoard(this, tmp);
    			/*
    			if(totalURL!=undefined && this.checkBlacklist(totalURL)){
    				$('#edita-cms-frame').hide();
    				return;
    			}
    			*/
    		}catch(e){
    		  alert("450");
    		  alert(e);
    		  console.error(e);
    		}

    	}catch(e){
    	  alert(e);
    	  console.error("457");
    		console.error(e);
    		this._bgPage[0].src = "/notice";
    	}
  }
  
}

/*
 *
 */
LayersOSToolbar.prototype.checkBlacklist = function(layerUrl){
	var blackList = new Array();
	blackList[0] = new Array('nytimes.com', "/img/layers_nytimes.gif");
	blackList[1] = new Array('twitter.com', "/img/layers_twitter.gif");
	blackList[2] = new Array('youtube.com', "/img/layers_youtube.gif");	
	blackList[3] = new Array('facebook.com', "/img/layers_facebook.gif");	
	
	//console.info(layerUrl);
	//console.info(blackList);
		
	// Check URL
	for (domain in blackList){
		if (layerUrl.indexOf(blackList[domain][0]) >= 0){
			os.showError('<img src="' + blackList[domain][1] + '" title="' + blackList[domain][0] +  '" /><br />We are working to support layers over <strong>' + blackList[domain][0] +  '</strong>. <br />We will keep you posted!', function(){window.location.href=totalURL;} );

			return true;			 
		}
	}
	return false;
}

/*
 * Adds wmode="transparent" to all embed tags and reloads the src 
 */
LayersOSToolbar.prototype.addWmodeToEmbeds = function(){	
	$(os.getBackgroundContent()).find('embed').each(function() {		
		var mySrc = $(this).attr('src');											
		$(this).attr('wmode','transparent');
		$(this).attr('src','null');		
		$(this).attr('src', mySrc);			
	});
}



/*
 * Creates and draws a new instance of the JoinForm
 */
LayersOSToolbar.prototype.drawJoinForm = function(){
	var tmp = this._displayable.find('#layersOS_dock_left_window');
	this._joinForm = new LayersOSJoinForm(this, tmp);
}



/*
 * Creates and draws a new instance of the JoinForm
 */
LayersOSToolbar.prototype.drawLoginForm = function(){
	var tmp = this._displayable.find('#layersOS_dock_left_window');
	this._loginForm = new LayersOSLoginForm(this, tmp);	
}



/*
 * Creates and draws a new instance of the edit title form
 */
LayersOSToolbar.prototype.drawEditTitleForm = function(){	
	var tmp = this._displayable.find('#layersOS_mylayer_title');
	
	if (!this._layerTitleForm) {
		this._layerTitleForm = new LayersOSEditTitleForm(this, tmp);
	}else{
		this._layerTitleForm._displayable.show();
	}
}

/*
 * Creates and draws a new instance of the identities list
 */
LayersOSToolbar.prototype.drawIdentitiesList = function(){
	var tmp = this._displayable.find('#layersOS_identities');	
	if (!this._identitiesAccordion) {
		this._identitiesAccordion = new LayersOSIdentitiesAccordion(this, tmp); //Defined in LayersOSAccordions.js
	}else{		
		this._identitiesAccordion._displayable.show();
	}
}

/*
 * Draws the layer information box
 */
LayersOSToolbar.prototype.drawLayerInfoBox = function(){
	
	if ( !this._infoBox ){
		var me = this;
		
		var currentLayer = os.getCurrentLayer();
		$('#layersOS_dock_center_logged').append(this._templates.getLayerInfoHTML(currentLayer));
		this._infoBox = $('#layersOS_current_layer_info');
		
		$('#layersOS_current_layer_info').find('.layersOS_list_close').click(
			function(){				
				$('#layersOS_current_layer_info').hide();
				me._infoButton._displayable.removeClass('layersOS_dock_item_selected');
				return false;
			}
		)
	}else{
		this._infoBox.show();
	}
		
}

/*
 * Creates and draws a new instance of the send email form
 */
LayersOSToolbar.prototype.drawSendEmailForm = function(){	
	
	if (!this._sendEmailForm) {
		
		var me = this;
				
		this._sendEmailForm = new LayersOSSendEmailForm(this, $('#layersOS_dock_center_logged') );
				
		$('#layersOS_send_email').find('.layersOS_list_close').click(
			function(){				
				me._sendEmailForm.cancelButtonClick();
				return false;
			}
		)
	}else{
		$('#layersOS_send_email').show();
	}
}

/*
 * Creates and draws a new instance of the comments box
 */
LayersOSToolbar.prototype.drawCommentsBox = function(){	
	
	if( this._commentsAccordion == undefined ){
		
		var me = this;
								
        this._commentsAccordion = new LayersOSCommentsAccordion(this, $('#layersOS_dock_center_logged'));			
		
		$('#layersOS_comments_box').find('.layersOS_list_close').click(
			function(){				
				$('#layersOS_comments_box').hide();
				me._commentButton._displayable.removeClass('layersOS_dock_item_selected');
				return false;				
			}
		)							
    }
	$('#layersOS_comments_box').show();
}

LayersOSToolbar.prototype.setTitleText = function(fullTitle){			
					
	if( fullTitle == '' || fullTitle == undefined ) {				
		fullTitle = STRING_layer_default_title;				 
	}
	
    var shortTitle = fullTitle;
    
    if (fullTitle.length > 20) {
        shortTitle = fullTitle.substring(0, 19) + '...';
    }						
    
	if( os.getCurrentLayer().getTitle() != fullTitle ){
		os.getCurrentLayer().setTitle(fullTitle);
	}
	
	// update dock item
	if (os.getCurrentLayer()._llink != ""){
		shortTitle = 'RE: ' + shortTitle;
	}
    $('#layersOS_dock_mylayer_title').text(shortTitle);
	
	// update form field
	$('#layersOS_mylayer_title_form [name=title]').val(fullTitle);
	
	// update alt text to title button
	this._layerTitleButton._displayable.attr("alt", fullTitle);	
			
}


LayersOSToolbar.prototype.hideActiveButtons = function(){
	// hide other windows				
	$('.layersOS_list').each(
		function(){
			$(this).hide();						
		}		
	);
	
	// remove selected class
	$('.layersOS_dock_item_selected').each(
		function(){
			console.info($(this));
			$(this).removeClass('layersOS_dock_item_selected');
		}
	);
}

/*
 * 
 */
LayersOSToolbar.prototype.setLoginData = function(user){
	this.drawLogged();
}

LayersOSToolbar.prototype.setLikedLayer = function(){	
	this._likeButton.switchIcon();
}

LayersOSToolbar.prototype.setReportedLayer = function(){	
	this._reportButton.switchIcon();
}

LayersOSToolbar.prototype.setCommentedLayer = function(){
    this._commentsAccordion.updateLastComment();
}

LayersOSToolbar.prototype.setSendEmail = function(){
	$("#layersOS_send_email").hide(); //ocultar el form
    this._sendEmailForm.enableSubmitButton();
}

LayersOSToolbar.prototype.dockItemEnable = function(item_id){
    $('#' + item_id).attr('class', 'layersOS_dock_item_clickable');
}

LayersOSToolbar.prototype.dockItemDisable = function(item_id){
    $('#' + item_id).attr('class', 'layersOS_dock_item_disabled');
}

LayersOSToolbar.prototype.populateLayersOverThisPage = function(layerIterator){	
	this._layersOverThisPageAccordion.updateLayerIterator(layerIterator);
}

LayersOSToolbar.prototype.populateMyLayersOverThisPage = function(layerIterator){		
	this._layersOverThisPageLoggedAccordion.updateLayerIterator(layerIterator, 'myLayers');
}

LayersOSToolbar.prototype.populateFriendsLayersOverThisPage = function(layerIterator){		
	this._layersOverThisPageLoggedAccordion.updateLayerIterator(layerIterator, 'myFriendsLayers');
}

LayersOSToolbar.prototype.populateOtherLayersOverThisPage = function(layerIterator){		
	this._layersOverThisPageLoggedAccordion.updateLayerIterator(layerIterator, 'otherLayers');
}

LayersOSToolbar.prototype.populateLayersByMyFriends = function(layerIterator){	
	this._myFriendsLayersAccordion.updateLayerIterator(layerIterator);
}

LayersOSToolbar.prototype.layerPublished = function(){
	os.showError(STRING_publish_form_ok);
	this._shareButton.disable();
	this._shareButton.setLabel(STRING_update_layer);
	this._infoButton.enable();
	this._emailButton.enable();
	this._commentButton.enable();
}
