// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


/* fix for $A is not defined on Firefox */
Function.prototype.safeBind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
	if (typeof $A == 'function')
    return __method.apply(object, args.concat($A(arguments)));
  }
}

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.unique()
//	- array.empty()
Array.prototype.unique = function () {
    for(i = 0; i < this.length; i++){
        for(j = this.length-1; j>i; j--){        
            if(this[i][0] == this[j][0]){
                this.splice(j,1);
            }
        }
    }
}

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

function _IsIE() { return /MSIE/.test(navigator.userAgent); }

if (!_IsIE()) {
  /** IDEA: http://www.codeproject.com/jscript/crossbrowserjavascript.asp **/
  HTMLElement.prototype.__defineGetter__("innerText", 
		  function () { return(this.textContent); });
  HTMLElement.prototype.__defineSetter__("innerText", 
		  function (txt) { this.textContent = txt; });
}

// -----------------------------------------------------------------------------------
   
function base_url() {
	var scripts = document.getElementsByTagName('script');
	var st_tag	= scripts[ scripts.length - 1 ];
	var uri_has = st_tag.src.match(/^(http:\/\/[^\/]+\/)/);	
	// return the base uri that is found.
	return (uri_has ? uri_has[0] : '/');
}

var BASE_URL = base_url();
// -----------------------------------------------------------------------------------

/**
 *  Attach the required tooltip function as where necessary.
 *  FIXME: Note that the following code should not take effect for Post Add page;
 *         as it may produce error.
 *			Blending is a slight variation of appearing. Ref: #1119
  */
if (!(/note\/(post|add)/).test(document.location)) {
	Event.observe(window, 'load', function(){
	  document.getElementsByClassName('tip_effect').each(function(element){
		new Tip(element, (element.alt?element.alt:element.ttip), { className: 'darktip', effect: 'blend' });
	  });
	}); 
	// FF doesn't accept the 'ttip' attribute for the anchor tag('x').
	// Hence the following workaround was made.
	Event.observe(window, 'load', function(){
	  document.getElementsByClassName('tip_effect_x').each(function(element){
		new Tip(element, 'Unsubscribe', { className: 'darktip', effect: 'blend' });
	  });
	});
	// For removing the channel.
	Event.observe(window, 'load', function(){
	  document.getElementsByClassName('tip_effect_y').each(function(element){
		new Tip(element, 'Delete', { className: 'darktip', effect: 'blend' });
	  });
	});
}

/* Refresh or reapply the tooltip for an element after loading the page
 *  say through Ajax calls, using this function. Ref: #1119-comment:6
  */
function tt_refresh(eid, msg) {
	var obj = (typeof(eid) == 'object' ? eid : $(eid));
	new Tip(obj, msg, { className: 'darktip', effect: 'blend' });
}

/* Attach the tooltip email-subscription icon; this function is used
 *  to attach the same on my-channels widget. Ref: #1119-comment:12
  */
var _TT_COUNT = 1;
function tt2_refresh(labels, msg) {
	// This avoids repetative calls.
	if (_TT_COUNT++ <= 1) return;
	// we're gonna dig into the <td> and find the image-element;
	//	then we attach a tooltip to it.
	var e1 = $(labels[1]);
	for(var i=0; i<e1.childNodes.length; i++) {
		if (!(/A/i).test(e1.childNodes[i].nodeName)) continue;
		a_obj = e1.childNodes[i].childNodes;
		for(var j=0; j<a_obj.length; j++) {
			if (!(/img/i).test(a_obj[j].nodeName)) continue;
			// here we attach the tooltip.
			tt_refresh(a_obj[j], msg);
		}		
	}
	// re-init when it reaches the delimiter.
	if (_TT_COUNT == 2) _TT_COUNT = 1;
}

//-----------------------------------------------------------------

/* Pastes a <div> on the specified container, so that the container
 *  is prevented from doing any actions; it looks like disabled part.
  */
var disable_it = function(div_id, loader) {	
	// construct the fake-div-id
	var fake_id = div_id + '_disabled';
	// build the fake-div or grab the existing
	var dup_div = $(fake_id);
	if(dup_div == null) {
		dup_div = document.createElement('div');
		dup_div.setAttribute('id', fake_id);
		document.body.appendChild(dup_div);
	}
	// now set some fixed styles for the fake-div
	var src = $(div_id);
	var offsets	= Position.cumulativeOffset(src);
    Element.setStyle(dup_div, {
      display: 'block',
	  position: 'absolute',
	  top: offsets[1]  + 'px',
	  left: offsets[0]  + 'px',
      width: src.offsetWidth + 'px',
	  height: (src.offsetHeight - (_IsIE() ? 33 : 0)) + 'px',
	  lineHeight: '25px',
	  zIndex: '1000000'
    });
	// these are the dynamic attributes
	dup_div.className = 'clsDisableIt';
	dup_div.title = 'Thank You, for Your patience!';
	
	var p_top = (src.offsetHeight /2) + 'px';		
	if (loader) {
		var img_path = BASE_URL+'images/indicator.gif';
		// preload and create loader image
		var img_preloader = new Image();		
		// if loader image found, create loadingimage
		img_preloader.onload=function(){			
			// Container
			var loader_div = document.createElement("div");
			loader_div.setAttribute('id','loader-div');
			dup_div.appendChild(loader_div);
			var pg_sz = getPageSize();
			Element.setStyle(loader_div, {
			  display: 'block',
			  position: 'relative',
			  top: (pg_sz[3]/1.5)+'px',
			  left: (pg_sz[2]/2.2)+'px',
			  width: '130px',
			  height: '30px',
			  zIndex: '2000000'
			});
		
			var loader_img = document.createElement("img");
			loader_img.src = img_path;
			loader_img.setAttribute('id','selLoaderImage');
			loader_img.style.position = 'absolute';
			loader_img.style.zIndex = '150';
			loader_div.appendChild(loader_img);
			//	clear onLoad, as IE will flip out w/animated gifs
			img_preloader.onload=function(){};
			
			var text_p = document.createElement("p");
			text_p.innerText = 'Please wait..';
			loader_div.appendChild(text_p);
			return false;
		}
		// just loading the loader image path.
		img_preloader.src = img_path;
	}/* else {
		// If suppose loader is not requested, put this message.
		dup_div.innerHTML = '<p style="position:relative;text-align:center;vertical-align:middle;border:0;padding:0;margin-top:'+p_top+'">This Post will not be shown to you from now. It\'s submitted to Admin.</p>';
	}*/
}

var enable_it = function(div_id ,loader) {
	// construct the fake-div-id
	var fake_id = div_id + '_disabled';
	// build the fake-div or grab the existing
	var dup_div = $(fake_id);
	if(dup_div != null) document.body.removeChild(dup_div);	
	return true;
}

//-----------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll() {

	var x_scroll, y_scroll;
	if (self.pageYOffset) {
		y_scroll = self.pageYOffset;
		x_scroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		y_scroll = document.documentElement.scrollTop;
		x_scroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		y_scroll = document.body.scrollTop;
		x_scroll = document.body.scrollLeft;	
	}

	return [x_scroll, y_scroll];
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var x_scroll, y_scroll;	
	if (window.innerHeight && window.scrollMaxY) {	
		x_scroll = window.innerWidth + window.scrollMaxX;
		y_scroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		x_scroll = document.body.scrollWidth;
		y_scroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		x_scroll = document.body.offsetWidth;
		y_scroll = document.body.offsetHeight;
	}

	var win_width, win_height;
	if (self.innerHeight) {	// all except Explorer
		win_width = (document.documentElement.clientWidth ? document.documentElement.clientWidth : self.innerWidth);
		win_height = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		win_width = document.documentElement.clientWidth;
		win_height = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		win_width = document.body.clientWidth;
		win_height = document.body.clientHeight;
	}	
	
	var pg_width, pg_height;
	// for small pages with total height less then height of the viewport
	pg_height = (y_scroll < win_height ? win_height : y_scroll);
	// for small pages with total width less then width of the viewport
	pg_width  = (x_scroll < win_width ? x_scroll : win_width);

	return [pg_width, pg_height, win_width, win_height];
}

// -----------------------------------------------------------------------------------
// Landing Page (newuser)
//  ----------------------------------------------------------------------------------

// Select all checkbox
function select_all_checkboxes(head_checkbox, form_id, prefix) {
    var form = $(form_id);
    checkboxes = form.getInputs('checkbox');
    checkboxes.each(function(e){ 
	    topic = new RegExp("^" + prefix);
	    if (topic.test(e.name)) {
		e.checked = head_checkbox.checked;
			}
	});
}
var InstallHelper = {

    build: false,
    
    clickedDownload: function() {
        
        //$('debug').innerHTML += "Clicked DL <br />";

        // VER NAVEGADOR

	InstallHelper.build = { url: "", size: "", platform: "", version: "We're sorry, your browser does not support Cooliris", browser: "ff", browserversion: "3", os: "lin", guid: "", majorVersion: "", buildVersion: ""};
        //$('debug').innerHTML += "Browser: " + InstallHelper.build.browser + "<br />";
        
        InstallHelper.windowHeight = window.innerHeight;
        
        // ADD STATS downloadClicked.
                
        if (InstallHelper.build.browser == 'ff') {
            return InstallHelper.ff_begin();
            
        } else if (InstallHelper.build.browser == 'ie') {
            return InstallHelper.ie_begin();

        } else if (InstallHelper.build.browser == 'sa') {
            return InstallHelper.sa_begin();

        } else {
            return InstallHelper.browser_not_supported();
        }
        return false;
        
    },    
    
    /**************
    
        FIREFOX
    
    **************/
    ff_begin: function() 
    {
        if (InstallHelper.ff_barPresent()) {
	   $('donwload_block_explanation').style.display = 'block';    
	} else {
	   $('donwload_block_explanation').style.display = 'none';    
	}
        setTimeout("InstallHelper.ff_begin()", 500);    
    },
    
    ff_barPresent : function() 
    {
        if (InstallHelper.windowHeight > window.innerHeight)
            return true;
        
        var diff = InstallHelper.firstWindowHeight - InstallHelper.windowHeight;
        
        return (diff != 0 && (diff < 35 || diff > -35) )
    
    }
};


// Check if the plugin download must be triggered and proceed accordingly.
// Works together with the install_plugin_script, see application_helper
// From the view, call first javascript_tag(install_plugin_script)
function trigger_download_if_needed() {
    // To be sure no browser will cache the result we'll add a timestamp to the GET request
    var url = '/front/check_trigger_download?' + new Date().getTime();
    new Ajax.Request(url, {
	    method: 'get',
		onSuccess: function(transport) {
		if (transport.responseText.match('true'))
		    start_install_plugin();			
			    }
    });
}