function getCookie(Name) { 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
	return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
}

function setCookie(name, cookie_value, days) {
	var expireDate = new Date()
	//set "expstring" to either future or past date, to set or delete cookie, respectively
	var expstring=(typeof days!="undefined")? expireDate.setDate(expireDate.getDate()+parseInt(days)) : expireDate.setDate(expireDate.getDate()-5)
	document.cookie = name+"="+cookie_value+"; expires="+expireDate.toGMTString()+"; path=/";
}

function deleteCookie(name){
	setCookie(name, "moot")
}



function loadSurchMeterToolTip(element, this_title, element_container) {
	var content = $(element_container).innerHTML;	
   	new Tip( element, 
            content, 
            {
 				title: 	this_title,
 				style: 	'surchur',
 				stem: 	'topLeft',
 				hook: 	{ tip: 'topLeft' },
 				offset: 	{ x: 100, y: 15 },
 				viewport: true,
 				border: 5,
 				radius: 5,
 				closeButton: 'true',
 				hideOn: { element: '.close',  event:  'mouseleave' },
 				showOn: 'click',
 				//hideOn: false,
 				hideAfter: 1,
 				borderColor: '#a3bd22',
 				width: 200
		 }
  );
}
function loadToolTips(){
document.observe('dom:loaded', function() {
	  $$('a.nfo').each(
	  function(element) {
	    new Tip( element, 
	             $(element.rel).innerHTML, 
	             {
	  				title: 	element.name,
	  				style: 	'protoblue',
	  				stem: 	false,
	  				hook: 	{ tip: 'topLeft', mouse: true },
	  				offset: 	{ x: 14, y: 14 },
	  				viewport: true,
	  				radius: 3,
	  				hideOn: 'mouseleave'
	  				
				 }
	   );
	 })
	});
}


function loadAToolTip(mainContainer){
		
	if(mainContainer == null || $(mainContainer) == null)return false;
	
	$(mainContainer).select('a.nfo').each(
	  function(element) {
		if($(element.rel)){
			temp_tool_tip = new Tip( element, 
		             $(element.rel).innerHTML, 
		             {
		  				title: 	element.name,
		  				style: 	'items',
		  				stem: 	false,
		  				offset: 	{ x: 14, y: 14 },
		  				viewport: true,
		  				radius: 3,
		  				hideOn: 'mouseleave'
					 }
			
		   );
			//by default deactivate all item tooltips without images
			if(element.hasClassName('imaged') == false){
				temp_tool_tip.deactivate();
				var is_imaged = 1;
			}
			else{
				var is_imaged = 2;
			}

			item_tooltips[item_tooltips.size()] = {'tip':temp_tool_tip, 'classi':is_imaged};
			temp_tool_tip = null;
		}
	 });
}

function load_dashboard_tooltips(mainContainer){
	  $(mainContainer).select('a.hot_nfo').each(
	  function(element) {
		if($(element.rel)){
			temp_tool_tip = new Tip( element, 
		             $(element.rel).innerHTML, 
		             {
		  				title: 	element.name,
		  				style: 	'items',
		  				stem: 	false,
		  				hook: 	{ tip: 'topLeft', mouse: true },
		  				offset: 	{ x: 10, y: 10 },
		  				viewport: true,
		  				radius: 3,
		  				hideOn: 'mouseleave'
					 }
			
		   );
		}
	 });
}

function deactivate_tool_tips(){
	if(typeof item_tooltips != 'undefined'){
		item_tooltips.each(function(elem){
			if(typeof(elem) == 'object'){
				if(elem.classi == 1){
					elem.tip.deactivate();
				}
			}
		});
	}
}
function reactivate_tool_tips(){
	item_tooltips.each(function(elem){
		if(elem.classi == 1){	
			elem.tip.activate();
		}
	})
}

function staticToolTip(element, this_title, element_container) {
	var content = $(element_container).innerHTML;	
   	new Tip( element, 
            content, 
            {
 				title: 	this_title,
 				style: 	'surchur',
 				stem: 	'topRight',
 				hook: 	{ tip: 'topRight' },
 				offset: 	{ x: 2, y: 15 },
 				viewport: true,
 				border: 5,
 				radius: 5,
 				closeButton: 'true',
 				hideOn: { element: '.close',  event:  'mouseleave' },
 				showOn: 'click',
 				//hideOn: false,
 				hideAfter: 1,
 				borderColor: '#a3bd22',
 				width: 200
		 }
  );
}

function staticToolTip4Goodies(element, this_title, element_container, position_to_right, have_stem) {

	if(element_container == null || $(element_container) == null)return false;
	
	var content = $(element_container).innerHTML;
	
	if(content == null)return false;
	
	if(have_stem == true){
		var my_stem = 'topMiddle';
		var my_y    = 10
	}
	else{
		var my_stem = '';
		var my_y    = 20;
	}

   	new Tip( element, 
            content, 
            {
 				title: 	this_title,
 				style: 	'surchur_goodies',
 				stem: 	my_stem,
 				hook: 	{ tip: 'topMiddle' },
 				offset: { x: position_to_right, y: my_y },
 				viewport: true,
 				border: 5,
 				radius: 5,
 				showOn: 'click',
 				//showOn: 'mousemove',
 				closeButton: 'true',
                hideOn: { element: '.close' , event:  'mouseleave'},
 				hideAfter: 1,
 				hideOthers: true,
 				borderColor: '#a3bd22'
		 }
  );
}

function handle_show(show_more_id, container_id){
	var lis = $(container_id).select('li.h_'+show_more_id);
	lis.each(function(element, index) {
		element.toggle();
	});
	if($('a_'+show_more_id).innerHTML == 'less'){
		$('a_'+show_more_id).innerHTML = 'more';
	}
	else{
		$('a_'+show_more_id).innerHTML = 'less';
	}
	return false;
}


function handle_ui_opt_events(li_id, a_id, panel_id, oid, act){
	if($(panel_id) == null){
		return false;
	}
	if(act=='show'){}	
	else{
		//show panel
		if($(a_id).hasClassName('OFF')){
			sources_settings['panels'][panel_id] = 1;
			var ef = new Effect.BlindDown(panel_id);
	        $(a_id).innerHTML = 'hide';
	        //update classes
	        $(a_id).removeClassName('OFF');
	        $(a_id).addClassName('ON');
			var op = new Effect.Opacity(li_id, {duration:0.2, from:0.5, to:1});
		}
		//hide panel
		else{
			sources_settings['panels'][panel_id] = -1;
			var ef = new Effect.BlindUp(panel_id);
	        $(a_id).innerHTML = 'show';
	
			//update classes
	        $(a_id).removeClassName('ON');
	        $(a_id).addClassName('OFF');
	
			var op = new Effect.Opacity(li_id, {duration:0.2, from:1.0, to:0.5});
		}
	}	
	return false;
}

function handle_nit(li_id, a_id, panel_id){
	if($(panel_id) == null){
		return false;
	}
	else{
	//show panel
		if($(a_id).hasClassName('OFF')){
		    var ef = new Effect.SlideDown(panel_id, { duration: 0.3 });
		    $(a_id).innerHTML = 'Click here to minimize Customize & Explore bar';
		  
		    //update classes
		    $(a_id).removeClassName('OFF');
		    $(a_id).addClassName('ON');
		 }
		
		//hide panel
		else{
			var ef = new Effect.SlideUp(panel_id, { duration: 0.3 });
		    $(a_id).innerHTML = 'Click Here to Customize & Explore';
		
			//update classes
		    $(a_id).removeClassName('ON');
		    $(a_id).addClassName('OFF');
		}
	}
	ef = null;
	return false;
}

function save_sources_settings(url){
	sources_settings['order'] 	= sources_order;
	var encoded_settings		= Object.toJSON(sources_settings);
    xhr(url+"/to_encode/'"+encoded_settings+"'", 
    		function(response){
    			encoded_settings = response; 
    			setCookie('sources_settings', encoded_settings, 360);
    			window.location.reload();
    		});
}

function restore_default_settings(){
	deleteCookie('sources_settings');
	window.location.reload();
}

/* === OVERLAY FUNCTIONS === */
function DialogOverlay(content, container) {
	 
	// Manage arguments and assign defaults,
	container = document.body;
	if (null == (this.container = $(container))) throw("container is not valid");
	
	// Assign instance variables
	this.content = $(content).innerHTML;
	this.overlay = new Element('div', { 'class': 'overlay' }).hide();
	this.dialog = new Element('div', { 'class': 'dialog' }).hide();
 
	// Hide the overlay when clicked. Ignore clicks on the dialog.
	//Event.observe(this.overlay, 'click', this.hide.bindAsEventListener(this));
	//Event.observe(this.dialog, 'click',  function(event) { Event.stop(event) });
 
	// Insert the elements into the DOM
	this.dialog.insert(this.content);
	this.container.insert(this.overlay);
	this.container.insert(this.dialog);
 
	// Content may have been hidden if it is embedded in the page
	this.dialog.hide();

}

DialogOverlay.prototype.show = function() {
	new Effect.Appear(this.overlay, { duration: 0.3,  to: 0.8 });
	this.dialog.show();
	return this;
};
DialogOverlay.prototype.hide = function(event) {
	this.dialog.hide();
	this.overlay.hide();
	return this;
};

DialogOverlay.prototype.timedClose = function(seconds, obj) {
	seconds = seconds * 1000;
	setTimeout(obj+'.hide();', seconds );
	return false;
};
/* === END - OVERLAY FUNCTIONS === */

function urlencode(str){
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };
 
    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();
 
    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

function search_wise(category){
	var keyword = $('keyword').value;
	if(keyword.length == 0){
		var uri = urlencode(category);
		$('cat_'+category).href = $('base_url').value + uri;
	}
	else{
		var uri = urlencode(category) + '/' + urlencode(keyword);
		$('cat_'+category).href = $('base_url').value + uri;
	}
}

function toggle_comments_for(hash){
	if($('comments_container_for_'+hash).visible()){
		$('comments_container_for_'+hash).hide();
		$('comments_toggler_'+hash).innerHTML = 'show all';
		$('comments_toggler_'+hash).removeClassName('bluer');
		$('comments_toggler_'+hash).addClassName('bluerw');
	}
	else{
		$('comments_container_for_'+hash).show();
		$('comments_toggler_'+hash).innerHTML = 'hide all';
		$('comments_toggler_'+hash).removeClassName('bluerw');
		$('comments_toggler_'+hash).addClassName('bluer');
	}
}
