// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


// Functions to automatically enter competitor name when user enters competitor url (when adding a new one) - 'NC' stands for new competitor
var nc_name_changed = false; // if the user alters the Name manually, this is set to true, unless the Name is blank
var nmc_name_changed = false; // separate variable for main competitor (since  both in window at same time)
function NC_URLChanged(main) {
  
  if ($('new_comp_title').value == '') {
    nc_name_changed = false; // reset if changed from previous submission
  }
    
  if ((main == '' && nc_name_changed == false) || (main != '' && nmc_name_changed == false)) {
    if (main == '') {
        var title = $('new_comp_link').value;
    } else {
        var title = $('new_main_comp_link').value;
    }
    title = title.replace(/^(?:https?:\/\/)?(?:www\.)?/i, ''); // gets rid of http://www (s and www are optional)
    
    if (title.match(/\.co\.uk/) || title.match(/\.(?:(?:au)|(?:nz))/i)) { // .co.uk and .*.au or .*.nz have different patterns than other domain suffixes
        title = title.replace(/\.[a-z]+\.[a-z]+(?:\/.*)?$/i, ''); // gets rid of any domain suffix and trailing paths
    } else {
        title = title.replace(/\.[a-z]+(?:\/.*)?$/i, ''); // gets rid of any domain suffix and trailing paths
    }
    
    // reverse the order of the name and put in title case (docs.google becomes Google Docs)
    var title_to_print = title.split('.');
    for (i=0;i<title_to_print.length;i++) {
	   title_to_print[i] = (title_to_print[i].substring(0,1)).toUpperCase() + title_to_print[i].substring(1);
	   if (title_to_print[i] == '') {
	       title_to_print.splice(i,1); // remove a blank element so it doesn't result in an extra space
	   }
    }
    if (title_to_print.length > 1) {
        title_to_print = title_to_print.reverse();
        title_to_print = title_to_print.join(' ');
    }
    
    if (main == '') {
        $('new_comp_title').value = title_to_print;
    } else {
        $('new_main_comp_title').value = title_to_print;
    }
  }
}

// changes the global variable nc_name_changed, so the name is not updated if it's been changed manually (but not cleared)
function NC_NameChanged(main) {
  if (main == '') {
    if ($('new_comp_title').value == '') {
        nc_name_changed = false;
    } else {
        nc_name_changed = true;
    }
  } else {
    if ($('new_main_comp_title').value == '') {
        nmc_name_changed = false;
    } else {
        nmc_name_changed = true;
    }
  }
}

// Loops through recent clippings and mark new ones since last visit
document.markNewClippings = function(e) {
  
    previous_login = getCookie('previous_login');
    // loop through the list elements of the activity log
    
    element = $('recent-clippings');
    element.cleanWhitespace();
    $A(element.childNodes).each(function(element) {
        user = element.getAttribute('_user');
        created = element.getAttribute('_created');
        if (User.id != user && created > previous_login) {
            element.className = 'blog-entry-new';
        }
    });
}

// Loops through activity log and mark new ones since last visit
document.markNewActivity = function(e) {
  
    previous_login = getCookie('previous_login');
    // loop through the list elements of the activity log
    
    element = $('activity_log');
    element.cleanWhitespace();
    $A(element.childNodes).each(function(element) {
        user = element.getAttribute('_user');
        created = element.getAttribute('_created');
        if (User.id != user && created > previous_login) {
            element.className = 'new';
        }      
    });
}

function setMainWindow() {
  window.name="mainWindow";
}

function focusNewCompetitor() {
  $('new_comp_link').focus();
}

function changeOpenerLocation(url) {
    if (window.opener && !window.opener.closed) {
        window.opener.location.href=url;
        window.opener.focus();
    }
}

function hideMatrixAlerts() {
    alerts = $$(".feature-alert");
    for (var i=0; i < alerts.length; i++) {
        alerts[i].style.display = 'none';
    }
    $('matrix_alert_link').innerHTML = '<a href="#" onclick="javascript:showMatrixAlerts();return false;">Show Feature Alerts</a>';
}

function showMatrixAlerts() {
    alerts = $$(".feature-alert");
    for (var i=0; i < alerts.length; i++) {
        alerts[i].style.display = 'inline';
    }
    $('matrix_alert_link').innerHTML = '<a href="#" onclick="javascript:hideMatrixAlerts();return false;">Hide Feature Alerts</a>';
}

function innerText(elem) {
	if (typeof(elem.text) != 'undefined')
		return elem.text;
	else if (typeof(elem.textContent) != 'undefined')
		return elem.textContent;
	else if (typeof(elem.innerText) != 'undefined')
		return elem.innerText;
}

function selectTextBox(id) {
 document.getElementById(id).select()
}

function setDisplayOfElement(element, display) {
    document.getElementById(element).style.display = display;
}

function uncheckElement(id) {
  $(id).checked = false;
}

function toggleSidebar() {
  if ($('sidebar-content-wrapper').style.display != 'block') {
    //$("sidebar-content-wrapper").style.display = 'none';
    $("sidebar-content-wrapper").style.display = 'block';
    //$("sidebar-content-wrapper").visualEffect("grow");
    //$("sidebar-content").style.display = 'block';
  } else {
    //$("sidebar-content").style.display = 'none';
    $("sidebar-content-wrapper").visualEffect("slide_left");
    //$("sidebar-content-wrapper").visualEffect("slide_up");
  }
}

function toggleFeatures(toggle_feature_on) {
    var e = $('feature-area');
    if(!($('features-showing'))) {
        toggle_feature_on();
        $('feature_toggle_arrow').innerHTML = '<img src="/images/triangle-down.gif" border="0">';
        $('feature_toggle_text').firstChild.nodeValue = '(click to hide)';
    } else {
        if (e.style.display == 'none') {
            $('feature_toggle_text').firstChild.nodeValue = '(click to hide)';
            $('feature_toggle_arrow').innerHTML = '<img src="/images/triangle-down.gif" border="0">';
            $("feature-area").visualEffect("blind_down", {"duration": 0.3});
        } else {
            $('feature_toggle_text').firstChild.nodeValue = '(click to show)';
            document.getElementById('feature_toggle_arrow').innerHTML = '<img src="/images/triangle-side.gif" border="0">';
            $("feature-area").visualEffect("blind_up", {"duration": 0.3});
        }
    }
}


function ToggleNewFeatureCategory() {
    if (document.getElementById('feature_category').value == 'add_new') {
        setDisplayOfElement('add-feature-new-category', 'block');
        $('new_feature_category').focus();
    } else { 
        setDisplayOfElement('add-feature-new-category', 'none');
    }
}

function ShowAddNewFeature() {
  $('show-add-feature-link').innerHTML = '<a class="internal-link-small" href="javascript: HideAddNewFeature()">Cancel add new feature</a>';
  $("add-feature-form-area").visualEffect("blind_down", {"duration": 0.3, afterFinish:  function(obj) {ToggleNewFeatureCategory();} });
}

function FastShowAddNewFeature() {
  $('show-add-feature-link').innerHTML = '<a class="internal-link-small" href="javascript: HideAddNewFeature()">Cancel add new feature</a>';
  $("add-feature-form-area").style.display = "block";
}

function HideAddNewFeature() {
  $('show-add-feature-link').innerHTML = '<a class="internal-link" href="javascript: ShowAddNewFeature()">Add new feature</a>';
  $("add-feature-form-area").visualEffect("blind_up", {"duration": 0.3});
}

function focusAddFeature() {
  document.getElementById('feature_name').focus();
}

function showSaveFeatureButton() {
    if ($("save-feature-button").style.display == 'none') {
        $("save-feature-button").visualEffect("appear", {"duration": 0.3});
    }
}

function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}

function ShowSetProjectURL() {
  $('set-project-url-link').innerHTML = '<a class="cancel-toggle" href="javascript: HideSetProjectURL()">Cancel</a>';
  $("set-project-url-form-area").visualEffect("blind_down", {"duration": 0.3});
}

function HideSetProjectURL() {
  $('set-project-url-link').innerHTML = '<a class="internal-link" href="javascript: ShowSetProjectURL()">Enter your company URL and name</a>';
  $("set-project-url-form-area").visualEffect("blind_up", {"duration": 0.3});
}



function BlogSearchCallback(searcher, id, numResults)
{
	this.searcher_ = searcher;
	this.id_ = id;
	this.numResults_ = numResults;
} 

BlogSearchCallback.prototype.searchComplete = function ()
{
	var rObj = $(this.id_);
	var results = this.searcher_.results;
	if (results.length == 0)
	{
		rObj.innerHTML = "<div class='empty'>No results.</div>";
	}
	else
	{
		rObj.innerHTML = "";
		for (var i=0; i < results.length && i < this.numResults_; i++)
		{
			blogResult = new BlogResult(results[i]);
			rObj.appendChild(blogResult.unselectedHtml());
		}
		if (i < results.length)
		{
			var showMoreLink = document.createElement("A");
			showMoreLink.href="#";
			showMoreLink.onclick = "return false;";
			showMoreLink.className="internal-link";
			showMoreLink.appendChild(document.createTextNode("View more posts..."));
			Event.observe(showMoreLink, 'mouseup', this.moreResults.bindAsEventListener(this));
			rObj.appendChild(showMoreLink);
		}
	}
	return false;
}

BlogSearchCallback.prototype.moreResults = function()
{
	this.numResults_ += 3;
	this.searchComplete();
}

function createSingleBlogResult(result)
{
	result_div = document.createElement("div");
	result_div.className = "blog-entry";
	
	title_div = document.createElement("div");
	title_div.className = "blog-entry-title";
	
	title = document.createTextNode(result.titleNoFormatting);
	title_link = document.createElement("a");
	title_link.href = result.postUrl;
	
	date_div = document.createElement("div");
	date_div.className = "blog-entry-date";
	pdate = new Date(result.publishedDate).toDateString();
	date = document.createTextNode(pdate)
	
	body_div = document.createElement("div");
	body_div.className = "blog-entry-body"
	body_div.appendChild(document.createTextNode(result.content));
	
	result_div.appendChild(title_div);
	title_div.appendChild(title_link);
	title_link.appendChild(title);
	
	result_div.appendChild(date_div);
	date_div.appendChild(date);
	
	result_div.appendChild(body_div);
	
	return result_div	
}



function BlogResult(result) {
  this.result_ = result;
  this.resultNode_ = this.unselectedHtml();
}

BlogResult.prototype.unselectedHtml = function() {
  var container = document.createElement("div");
  container.className = "blog-entry";
  container.appendChild(this.result_.html.cloneNode(true));
  var saveDiv = document.createElement("div");
  saveDiv.className = "comment-this";
  saveDiv.innerHTML = "clip this";
  Event.observe(saveDiv, 'click', document.ClipResult.bindAsEventListener(this.result_));
  container.appendChild(saveDiv);
  container.result = this.result;
  return container;
}

function remove_if_exists (element) {
	if ($(element))
    	Element.remove($(element));
}



function limitCheckboxes(obj,max) {
    var count=0;
    for (var i=0; i < obj.form.elements.length; i++) {
        var element = obj.form.elements[i];
        count += element.checked
    }
    if (count > max) {
        obj.checked = false;
        alert('Only ' + max + ' competitors can be graphed at once.\nUnselect one of the current selections to show this competitor.');
    }
    
    // also hide "saved" message
    $('save_message').innerHTML = '';
}



function RND(tmpl, ns, scope) {
  scope = scope || window;
  var fn = function(w, g) {
    g = g.split("|");
    var cnt = ns[g[0]];
    for(var i=1; i < g.length; i++)
      cnt = scope[g[i]](cnt);
    if(cnt == 0 || cnt == -1)
      cnt += '';
    return cnt || w;
  };
  return tmpl.replace(/(?:%|%25)(?:\(|%28)([A-Za-z0-9_|.]*)(?:\)|%29)/g, fn);
}

var _unique_id = 1;
function unique_id(){
	return _unique_id++;
}

function render_js_template(template,ns,scope){
	if (typeof(template) == 'string')
		template = $(template).value;
	
	if (!ns)
		ns = "NID_"+unique_id();
	
	if (typeof(ns) != 'object')
		ns = {'id':ns};
	return RND(template,ns,scope)
}

function render_js_template_to_node(template,ns,scope){
	el = document.createElement("div");
	el.innerHTML = render_js_template(template,ns);
	return el;
}

var _content_before_loading = {};
var _loading_html = "<div class='thinking-gif'><img src='/images/thinking-spacer.gif'></div>"
function show_loading_icon(id)
{
	_content_before_loading[id] = $(id).innerHTML;
	Element.update(id, _loading_html)
}

function hide_loading_icon(id)
{
	Element.update(id, _content_before_loading[id]);
	_content_before_loading[id] = null;
}


function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

var CompetitorSelectors = Class.create();
CompetitorSelectors.prototype = {

	// array of competitors (name,id)
	tbody : null,
	competitor_list : new Array(),
	used_competitors : null,
	
	initialize: function(tbody,competitors,data) {
		this.tbody = tbody;
		this.competitor_list = competitors;
		
		// iterate over the data and build selectors
		data.each(function(competitor){
			this._createSelector(competitor.id,competitor.sentiment);
		}.bind(this));
		
		this._cleanupSelectors();
	},
	
	_createSelector: function(selected,sentiment) {
		tr = document.createElement("TR");
		this.tbody.appendChild(tr);
		td = document.createElement("TD");
		tr.appendChild(td);
		select = document.createElement("select");
		select.className="select-box"
		select.name="competitor_ids[]";
		td.appendChild(select);
		this._updateSelectorOptions(select);
		if (selected)
		{
			select.value = selected;
			this._createSentimentSlider(select,sentiment);
		}
		
		Event.observe(select,"change",this._cleanupSelectors.bind(this));
	},
	
	_removeSentimentSlider: function(selector)
	{
		tr = selector.parentNode.parentNode;
		if (tr.childNodes.length > 1)
			Element.remove(tr.childNodes[1]);
	},
	
	_createSentimentSlider: function(selector,sentiment)
	{
		tr = selector.parentNode.parentNode;
		
		if (tr.childNodes.length > 1) return;
		
		// create the sentiment selector
		td2 = document.createElement("TD");
		tr.appendChild(td2);
		
		var slider = document.createElement("DIV");
		slider.className = sentiment ? "slider" : "slider_inactive";
		slider.id = "slider_"+Math.floor(Math.random()*99999);
		td2.appendChild(slider);
		
		var slider_left = document.createElement("DIV");
		slider_left.className = "slider_left";
		slider.appendChild(slider_left);
		
		var slider_handle = document.createElement("DIV");
		slider_handle.id = "slider_handle_"+Math.floor(Math.random()*99999);
		slider_handle.className = "slider_handle";
		slider.appendChild(slider_handle);
		
		// add a hidden field to store the value of the sentiment selector
		var hidden = document.createElement("INPUT");
		hidden.type = "hidden";
		hidden.name="competitor_sentiments[]";
		td2.appendChild(hidden);
		
		// create the status td
		td3 = document.createElement("TD");
		tr.appendChild(td3);
		
		var status_container = document.createElement("DIV");
		status_container.className="slider-status";
		td3.appendChild(status_container);
		
		var status = document.createElement("DIV");
		status.className="sentiment-unset";
		status_container.appendChild(status);
		
		status.innerHTML = "N/A";
		
		// now add the slider element
		var sliderLimited = new Control.Slider(slider_handle.id,slider.id, {range:$R(1,5)});
		
			
		sliderLimited.options.onSlide = function(value) {
			slider.className = "slider";
	        if (value < 1.5) { status.innerHTML = "very negative"; status.className = "sentiment-very-negative"; }
	        else if (value < 2.5) { status.innerHTML = "negative"; status.className = "sentiment-negative"; }
	        else if (value < 3.5) { status.innerHTML = "neutral"; status.className = "sentiment-neutral"; }
	        else if (value < 4.5) { status.innerHTML = "positive"; status.className = "sentiment-positive"; }
	        else { status.innerHTML = "very positive"; status.className = "sentiment-very-positive"; }
    	};
    	
    	if (sentiment) {
    		hidden.value = sentiment;
			sliderLimited.setValue(sentiment);
			sliderLimited.options.onSlide(sentiment);
		}
		else
			sliderLimited.setValue(3);
		
    	// make it snap to the correct values at the end of the slide
    	sliderLimited.options.onChange = function(value) {
    		var nvalue = null;
    		if (!(value == 1 || value == 2 || value == 3 || value == 4 || value == 5))
    		{
		        if (value < 1.5 && value != 1) { nvalue = 1; }
		        else if (value < 2.5 && value != 2) { nvalue = 2; }
		        else if (value < 3.5 && value != 3) { nvalue = 3; }
		        else if (value < 4.5 && value != 4) { nvalue = 4; }
		        else if (value != 5) { nvalue = 5; }
		        
		        if (nvalue)
		        {
		        	sliderLimited.setValue(nvalue);
		        	value = nvalue;
		        }
	        }
	        
	        hidden.value = value;
	        
	        sliderLimited.options.onSlide(value);
    	};
    	
    	
    	
	},
	
	competitors : function() {
		return this._selectors().pluck("value").reject(function(v){return v==""});
	},
	
	_competitorCount: function() {
		var count = 0;
		this._selectors().each(function(selector) {
			if (selector.value != "") count++;
		});
		return count;
	},
	
	_selectors: function() {
		return $A(this.tbody.childNodes).collect(function(tr) {
			return tr.firstChild.firstChild; //tr.td.select
		});
	},
	
	_updateSelectorOptions: function(select) {
		var oldValue = select.value;

		select.innerHTML = ""; // remove the current options;
		
		option = document.createElement("OPTION");
		option.value = "";
		select.appendChild(option);
			
		this.competitor_list.each(function(competitor){
			if (
				competitor[1] == oldValue || 
				!(this.used_competitors && this.used_competitors[competitor[1]])
				)
			{
				option = document.createElement("OPTION");
				option.value = competitor[1];
				option.appendChild(document.createTextNode(competitor[0]));
				select.appendChild(option);
			}
		}.bind(this));
		select.value = oldValue;
	},
	
	_removeSelector : function(selector) {
		Element.remove(selector.parentNode.parentNode);
	},
	
	_cleanupSelectors: function() {
		// remove blank selectors
		selectors = this._selectors();
		selector_count = selectors.length;
		for (var i = 0; i < selector_count; i++) {
			var selector = selectors[i];
			if (selector.value == "") { 
				if (i < selector_count-1)
					this._removeSelector(selector);
				else
					this._removeSentimentSlider(selector);
			}
			else {
				this._createSentimentSlider(selector);
			}
		}
	
		// reset unsed competitors
		this._resetUsedCompetitors();
	
		// update selector options
		this._selectors().each(function(selector) {
			this._updateSelectorOptions(selector);
		}.bind(this));
		
		// add blank selector if needed
		selector_count = this._selectors().length;
		if (selector_count == this._competitorCount() && selector_count != this.competitor_list.length)
			this._createSelector();
	},
	
	_resetUsedCompetitors: function() {
		this.used_competitors = new Array();
		this.competitors().each(function (id){
			this.used_competitors[id] = true;
		}.bind(this))
	}
}

function update_competitor_select_options(competitors) {
	// competitor selectors is a tbody so we need to remove the children one by one for ie
	cs = $("competitor-selectors");
	for (var i = 0; i < cs.childNodes.length; i++)
		cs.removeChild(cs.childNodes[i]);
	
	new CompetitorSelectors(
		cs,
		competitors,
		[]);
}

function toggleActionLink(a) {
	cancel_text = a.cancel_text;
	if (cancel_text) {
		original_text = a.innerHTML;
		a.innerHTML = cancel_text;
		a.cancel_text = original_text;
	}
	original_class = a._original_class;
	if (original_class != null && original_class != 'no-class') {
		a._original_class = 'no-class';
		a.className = original_class;
	}
	else {
	    a._original_class=a.className;
		a.className = a.className + " cancel";
	}
}