/*
 * Global javascript framework to handle jquery requests [ajax-json-xml]
 * [br] Framework em javascript criado para manipular requisições jquery [ajax-json-xml]
 * Revision: 1.0.1
 *
 * Created by Rafael Mussi on 2010-06-23. Please report any bug to rafaelmussi[at]gmail[dot]com
 *
 * Copyright (c) 2010 - Rafael Mussi (http://www.rafaelmussi.com.br)
 *
 * $Id: RMall.js 1.0.1 2010-06-23 13:26:16Z rafaelmussi[at]gmail[dot]com $
 *
 */
// file: RMall.js
if (typeof RM == 'undefined') {
	RM = {};
}

//--- start RMlang.js ---
// check to be sure the RM global object already exists
if (typeof RM == "undefined" || !RM) {
    alert('You must include the RM global object before including lang.js!');
}
else {
		 
	/**
		The lang module is used for i18n in the cjt.  It contains values in english that can be overwritten on the page.
		@module lang
	*/

	/**
		The lang module is used for i18n in the cjt.  It contains values in english that can be overwritten on the page.  Note: I do not include yuidoc-style comments for this section; if you want to see the phrases check the code directly.
		@class lang
		@namespace RM
		@extends RM
	*/
	RM.lang = {
		
		// general purpose
		Thank_you : "Muito obrigado!",
		Thanks: "Obrigado!",
		thank_you : "muito obrigado.",
		thanks: "obrigado.",
		close : "fechar",
		Close : "Fechar",
		cancel : "cancelar",
		unlimited : "ilimitado",
		or : "ou",
		ajax_loading : "carregando...",	

		// create strong password dialog box
		password_generator : "Password Generator",
		generate_password : "Generate Password",
		advanced : "advanced",
		confirm_copy_password : "I have copied this password in a safe place.",
		use_password : "Use Password",
		length : "Length",
		alpha_characters : "Alpha Characters",
		nonalpha_characters : "Non Alpha Characters",
		both : "Both",
		lowercase : "Lowercase",
		uppercase : "Uppercase",
		numbers : "Numbers",
		symbols : "Symbols",
		password_strength : "Password Strength",
		passwords_match : "Passwords Match",
		password_validator_strength : "Password strength must be at least",
		password_validator_no_spaces : "Password cannot have spaces.",
		password_validator_no_empty : "Password cannot be empty.",
		password_validator_no_match : "Passwords do not match.",

		// password bar strength phrases
		strength_phrase_very_weak : "Very Weak",
		strength_phrase_weak : "Weak",
		strength_phrase_ok : "OK",
		strength_phrase_strong : "Strong",
		strength_phrase_very_strong : "Very Strong",

		// status widget
		click_to_close : "clique para fechar",
		
		// toggle_more_less function
		toggle_more : "mais &raquo;",
		toggle_less : "menos &raquo;",
		
		// contato phrases
		contato_added : "Sua mensagem foi enviada com sucesso! Em breve entraremos em contato!",
		
		//comentario
		comentario_added : "Seu comentário foi enviado com sucesso. Aguarde a aprovação para vê-lo no site!",
		
		//indique
		indicar_added :  "Sua indicação desse conteúdo foi enviado com sucesso.!",
		
		// orcamento phrases
		orcamento_added : "Sua solicitação foi enviada com sucesso! Em breve entraremos em contato!",
		
		// trabalhe phrases
		trabalhe_added : "Seu currículo foi cadastrado em nosso sistema!",
		
		// mural phrases
		mural_added : "Seu recado foi enviado com sucesso e em breve ele estará disponível no site!",
		
		// indique phrases
		indique_added : "Indicação enviada com sucesso!",
		
		// newsletter phrases
		newsletter_added : "Email cadastrado com sucesso!",
		newsletter_removed : "Email removido com sucesso!",
		
		// generic error messages
		Error : "Erro",
		json_error : "Erro na solicitação JSON",
		json_parse_failed : "JSON parse failed.",
		ajax_error : "Erro na solicitação AJAX",
		ajax_try_again : "Por favor recarregue a página e tente novamente."
		
	} // end lang object
} // end else statement
//--- end RMlang.js ---

//--- start RMjson.js ---
// check to be sure the RM global object already exists
if (typeof RM == "undefined" || !RM) {
    alert('You must include the RM global object before including json.js!');
}
/* else if (typeof YAHOO.lang.JSON == "undefined" || !YAHOO.lang.JSON) {
    alert('You must include the YUI JSON library before including json.js!');
} */
else {
		 
	/**
		The json module contains properties that reference json for our product.
		@module json
	*/

	/**
		The json class contains properties that reference json for our product.
		@class json
		@namespace RM
		@extends RM
	*/
	var NativeJson = Object.prototype.toString.call(this.JSON) === '[object JSON]' && this.JSON;

	RM.json = {

		// Native or YUI JSON Parser
		fastJsonParse: function (s, reviver) {
			return NativeJson ?  
			NativeJson.parse(s,reviver) : jQuery.parseJSON(s);
		}


		
	} // end json object
} // end else statement
//--- end RMjson.js ---


//--- start RMicons.js ---
// check to be sure the RM global object already exists
if (typeof RM == "undefined" || !RM) {
    alert('You must include the RM global object before including icons.js!');
}
else {
    
	/**
		The icons module contains properties that reference icons for our product.
		@module icons
	*/

	/**
		The icons class contains properties that reference icons for our product.
		@class icons
		@namespace RM
		@extends RM
	*/
	RM.icons = {
		 /** /cPanel_magic_revision_XXXXX/ is used to allow caching of images -- XXXXX needs to be incremented when the image changes **/
		
		/**
			Error icon located at cjt/images/icons/error.png
			@property error
			@type string
		*/
		error : '<img src="area_publica/jsf/jquery/images/icons/error.png" alt="error" />',
		error_src : 'area_publica/jsf/jquery/images/icons/error.png',
			
		/**
			success icon located at cjt/images/icons/success.png
			@property success
			@type string
		*/	
		success : '<img src="area_publica/jsf/jquery/images/icons/success.png" alt="success" />',
		success_src : 'area_publica/jsf/jquery/images/icons/success.png',

		/**
			warning icon located at cjt/images/icons/warning.png
			@property warning
			@type string
		*/	
		warning : '<img src="area_publica/jsf/jquery/images/icons/warning.png" alt="warning" />',
		warning_src : 'area_publica/jsf/jquery/images/icons/warning.png',
		
		/**
			AJAX loading icon located at cjt/images/ajax-loader.gif
			@property ajax
			@type string
		*/
		ajax : '<img src="area_publica/jsf/jquery/images/ajax-loader.gif" alt="loading" />',
		ajax_src : 'area_publica/jsf/jquery/images/ajax-loader.gif',
		
		// /cjt/images/1px_transparent.gif
		transparent : '<img src="area_publica/jsf/jquery/images/1px_transparent.gif" alt="" />',
		transparent_src : 'area_publica/jsf/jquery/images/1px_transparent.gif'
		
	} // end icons object
} // end else statement

//--- end RMicons.js ---

//--- start RMutil.js ---
// check to be sure the RM global object already exists
if (typeof RM == "undefined" || !RM) {
	 alert('You must include the RM global object before including array.js!');
}
else {
	/**
		The util module contains miscellaneous utilities.
		@module array
	*/

	/**
		The util module contains miscellaneous utilities.
		@class util
		@namespace RM
		@extends RM
	*/
	RM.util = {
		
		// Catches the "enter" key when pressed in a text field.  Useful for simulating native <form> behavior.
		catch_enter : function(els, func) {
			// if func is a string, assume it's a submit button
			if (typeof(func) == "string") {
				var submit_button = func;
				var press_button = function() {
					YAHOO.util.Dom.get(submit_button).click();
				};
				func = press_button;
			}
			var _catch_enter = function(e, o) {
				var key = YAHOO.util.Event.getCharCode(e);
				if (key == 13) o.func();
			};
			YAHOO.util.Event.on(els, "keyup", _catch_enter, { func: func });
		},
		
		// initialize a second-decreasing countdown
		countdown_timeouts : [],
		countdown : function(el, after_func) {
			var seconds_el = $("#"+el);
			if (! seconds_el) return;
			
			var second_decrease = function() {
				if (seconds_el) {
					var seconds = parseInt(seconds_el.html());
					if (seconds == 0) {
						after_func();
					}
					else {
						seconds_el.html(seconds - 1);
						RM.util.countdown_timeouts[seconds_el.id] = setTimeout(second_decrease, 1000);
					}
				}
			};
			clearTimeout(this.countdown_timeouts[seconds_el.id]);
			this.countdown_timeouts[seconds_el.id] = setTimeout(second_decrease, 1000);
		},
		
		 // print_r for JavaScript
		dump : function(arr, level) {
			var dumped_text = "";
			if(!level) level = 0;
			
			//The padding given at the beginning of the line.
			var level_padding = "";
			for(var j=0;j<level+1;j++) level_padding += "    ";
			
			if(typeof(arr) == 'object') { //Array/Hashes/Objects 
				for(var item in arr) {
					var value = arr[item];
					
					if(typeof(value) == 'object') { //If it is an array,
						dumped_text += level_padding + "'" + item + "' ...\n";
						dumped_text += dump(value,level+1);
					} else {
						dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
					}
				}
			} else { //Stings/Chars/Numbers etc.
				dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
			}
			return dumped_text;
		},
		
		convert_breaklines : function(str) {
			return str.replace(/\n/, "<br />");
		},
		
		operating_system : function() {
			if (navigator.userAgent.search(/Win/) != -1) {
				return "Windows";
			}
			if (navigator.userAgent.search(/Mac/) != -1) {
				return "Mac";
			}	
			if (navigator.userAgent.search(/Linux/) != -1) {
				return "Linux";
			}
			return "Unknown";
		}	
		
	} // end util object
} // end else statement

//--- end RMutil.js ---

//--- start RMurls.js ---
// check to be sure the RM global object already exists
if (typeof RM == "undefined" || !RM) {
    alert('You must include the RM global object before including urls.js!');
}
else {
		 
	/**
		The urls module contains URLs for AJAX calls.
		@module urls
	*/

	/**
		The urls class URLs for AJAX calls.
		@class urls
		@namespace RM
		@extends RM
	*/
	RM.urls = {
		
		/**
			URL for the password strength AJAX call.<br />
			GET request<br />
			arg1: password=password
			@property password_strength
			@type string
		*/
		password_strength : function() {
					return RM.base_path() + "backend/passwordstrength.cgi";
			  },
		
		// build a JSON API call from an object
		json_api : function(object) {
			
			// build the query string
			var query_string = '';
			for (var item in object) {
				query_string += item + '=' + encodeURIComponent(object[item]) + '&';
			}
			
			// add some salt to prevent browser caching		
			query_string += 'cache_fix=' + new Date().getTime();
			
			return RM.base_path() + 'json-api/?' + query_string;
		},
		
		whm_api : function(script, params, api_mode) {
			if (! api_mode) {
				api_mode = "json-api";
			}
			else if (api_mode == "xml") {
				api_mode = "xml-api";
			}

			// build the query string
			// TODO: turn this into a general object->query string function
			// 		 also have a query params -> object function
			var query_string = '';
			for (var item in params) {
				query_string += item + '=' + encodeURIComponent(params[item]) + '&';
			}
			
			// add some salt to prevent browser caching		
			query_string += 'cache_fix=' + new Date().getTime();		
			
			return RM.base_path() + api_mode + "/" + script + "?" + query_string;
		}
		
	} // end urls object
} // end else statement
//--- end RMurls.js ---

//--- start RMwidgets.js ---
// check to be sure the RM global object already exists
if (typeof RM == "undefined" || !RM) {
    alert('You must include the RM global object before including widgets.js!');
}
// check to be sure the RM JSON library exists
else if (typeof RM.json == "undefined" || !RM.json) {
    alert('You must include the RM json.js library before including password.js!');
}
else {
    
	/**
		The widgets module contains widget objects used in cPanel.
		@module widgets
	*/

	/**
		The widgets class contains widget objects used in cPanel.
		@class widgets
		@namespace RM
		@extends RM
	*/
	RM.widgets = {

		 // show a progress bar
		progress_bar : function(elm, percentage, text, options) {
			
			// just a legacy thing so I don't have to backmerge a change for 11.25
			if (options == '{"inverse_colors":"true"}') {
				options = { inverse_colors : true };
			}
			
			if (! options) options = {};
			if (! options.text_style) options.text_style = "";
			if (! options.inverse_colors) options.inverse_colors = false;
			if (! options.one_color) options.one_color = false;
			
			// clean the percentage
			percentage = parseInt(percentage);
			if (percentage < 0) percentage = 0;
			if (percentage > 100) percentage = 100;
			  
			  // get the element
			  //el = YAHOO.util.Dom.get(elm);
			  el = $("#"+elm);
			
			// set the color of the bar
			var color;
			if (percentage >= 0)  color = '#FF0000';	// red
			if (percentage >= 20) color = '#FF9837';	// orange
			if (percentage >= 40) color = '#F1FF4D';	// yellow
			if (percentage >= 60) color = '#C5FF00';	// chartreuse
			if (percentage >= 80) color = '#8FFF00';	// lt green
			  
			  if (options.inverse_colors) {
					if (percentage >= 0)  color = '#8FFF00';	// lt green
					if (percentage >= 20) color = '#C5FF00';	// chartreuse
					if (percentage >= 40) color = '#F1FF4D';	// yellow
					if (percentage >= 60) color = '#FF9837';	// orange
					if (percentage >= 80) color = '#FF0000';	// red
			  }
			  
			  if (options.one_color) {
					color = options.one_color;
			  }
			
			var height = "100%";
			// BROWSER-SPECIFIC CODE: manually get the height from the parent element for ie6
			if (YAHOO.env.ua.ie == 6) {
				var div_region = YAHOO.util.Region.getRegion(el);
				height = div_region.height + "px";
			}
			
			var html;
			// container div with relative positioning, height/width set to 100% to fit the container element
			html  = '<div class="cpanel_widget_progress_bar" style="position: relative; width: 100%; height: ' + height + '; padding: 0px; margin: 0px; border: 0px">';
			
			// text div fits the width and height of the container div and has it's text vertically centered; has an opaque background and z-index of 1 to put it above the color bar div
			  if (text) {
					html += '<div style="position: absolute; left: 0px; width: 100%; height: ' + height + '; padding: 0px; margin: 0px; border: 0px; z-index: 1; background-image: url(\'area_publica/jsf/jquery/images/1px_transparent.gif\')">';
					html += '<table style="width: 100%; height: 100%; padding: 0px; margin: 0px; border: 0px">';
					html += '<tr><td valign="middle" style="padding: 0px; margin: 0px; border: 0px;">'; // use a table to vertically center for greatest compatability
					html += '<div style="width: 100%; ' + options.text_style + '">' + text + '</div>';
					html += '</td></tr></table>';
					html += '</div>';
			  }

			// color bar div fits the width and height of the container div and width changes depending on the strength of the password
			  if (percentage > 0) {
				html += '<div style="position: absolute; left: 0px; top: 0px; width: ' + percentage + '%; height: ' + height + '; background-color: ' + color + '; padding: 0px; margin: 0px; border: 0px"></div>';
			  }
			
			// close the container div
			html += '</div>';
			
			// save the percent information in a hidden div
			html += '<div class="cpanel_widget_progress_bar_percent" style="display: none">' + percentage + '</div>';
			
			el.innerHTML = html;
		},
		
		// variable used to hold the status box overlay widget
		status_box : null,
		
		// variable used to hold the status box overlay's timeout
		status_box_timeout : null,
		
		status : function(message, class_name) {
			
			// if the status bar is currently being displayed clear the previous timeout
			clearTimeout(this.status_box_timeout);
			
			var options = {
				zIndex:1000,
				visible: true,
				effect: {effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25}
			};
			this.status_box = new YAHOO.widget.Overlay("cpanel_status_widget", options);
			this.status_box.setBody('<span class="cpanel_status_widget_message">' + message + '</span>');

			var footer = '<br /><div style="width: 100%; text-align: right; font-size: 10px">';
			footer += RM.lang.click_to_close + ' [<span id="cpanel_status_widget_countdown">10</span>]';
			footer += '</div>';
			this.status_box.setFooter(footer);
			this.status_box.render(document.body);

			YAHOO.util.Dom.removeClass("cpanel_status_widget", "cpanel_status_success");
			YAHOO.util.Dom.removeClass("cpanel_status_widget", "cpanel_status_error");
			YAHOO.util.Dom.removeClass("cpanel_status_widget", "cpanel_status_warning");
			if (class_name) {
				YAHOO.util.Dom.addClass("cpanel_status_widget", "cpanel_status_" + class_name);
			}
			else {
				YAHOO.util.Dom.addClass("cpanel_status_widget", "cpanel_status_success");
			}
			
			var hide_me = function() {
				RM.widgets.status_box.hide();
				clearTimeout(RM.widgets.status_box_timeout);
			};
			
			YAHOO.util.Event.on("cpanel_status_widget", "click", hide_me);

			var second_decrease = function() {
				var seconds_el = YAHOO.util.Dom.get("cpanel_status_widget_countdown");
				if (seconds_el) {
					var seconds = parseInt(seconds_el.innerHTML);
					
					// close the window when the countdown is finished
					if (seconds == 0) {
						hide_me();
					}
					// else decrease the counter and set a new timeout
					else {
						seconds_el.innerHTML = seconds-1;
						CPANEL.widgets.status_box_timeout = setTimeout(second_decrease, 1000);
					}
				}
			};

			// initialize the first timeout
			this.status_box_timeout = setTimeout(second_decrease, 1000);
		},
		
		// status_bar widget
		/*
		var status_bar_options = {
			duration : integer,
			callbackFunc : function literal,
			hideCountdown : true,
			noCountdown : true,
			rawHTML : HTML string
		}
		*/
		status_bar : function(elm, style, title, message, options) {
			var duration = 5;
			if (style == "error") duration = 10;
			
			// options
			var callback_func = function() {};
			var hide_countdown = false;
			var countdown = true;
			var raw_html = false;
			var show_icons = false;
			if (options) {
				if (options.duration) duration = options.duration;
				if (options.callbackFunc) {
					if (typeof(options.callbackFunc) == "function") callback_func = options.callbackFunc;
				}
				if (options.hideCountdown) hide_countdown = true;
				if (options.showIcons) show_icons = true;
				if (options.rawHTML) raw_html = options.rawHTML;
				if (options.noCountdown) countdown = false;
			}
			
			el = $("#"+elm);
			
			var hide_bar = function() {
				el.slideUp("normal", function() {
					el.html('');
					callback_func();
					//RM.align_panels_event.fire();
				});
			};
			
			// set the style class
			el.removeClass("rmc_status_bar_success");
			el.removeClass("rmc_status_bar_error");
			el.removeClass("rmc_status_bar_warning");
			el.addClass("rmc_status_bar_" + style);
			
			var status = '';
			if (raw_html == false) {
				if (show_icons == true){
					status = RM.icons.success;
					if (style == "error") status = RM.icons.error;
					if (style == "warning") status = RM.icons.warning;
				}
				status += " <strong>" + title + "</strong>";
				if (message) {
					if (message != "") {
						status += '<div style="height: 5px"></div>';
						status += RM.util.convert_breaklines(message);
					}
				}
			}
			else {
				status = raw_html;
			}		
			
			var countdown_div = '';
			if (countdown == true) {
				countdown_div = '<div class="rmc_status_bar_countdown"';
				if (hide_countdown == true) countdown_div += ' style="display: none"';
				countdown_div += '>'+RM.lang.click_to_close+' [<span id="' + el.attr('id') + '_countdown">' + duration + '</span>]</div>';
			}
			else {
				countdown_div = '<div class="rmc_status_bar_countdown">'+RM.lang.click_to_close+'</div>';
			}
			
			el.html(status + countdown_div);
			
			el.slideDown("normal", function() {
				// give the status bar element "hasLayout" property in IE
				el.css("zoom", '1');
				
				if (countdown == true) RM.util.countdown(el.attr('id') + "_countdown", hide_bar);
				//RM.align_panels_event.fire();
			});
			el.click(function(){
				hide_bar();
			});
			
			/*
			<div id="add_#MODULO#_status_bar" style="display: none;" class="rmc_status_bar rmc_status_bar_warning">
				<img src="area_restrita/imagens/accept.png" alt="error"> <strong>#MODULO.MSG1#</strong>
				<div style="height: 5px;"></div>#MODULO.MSG2#
				<div class="rmc_status_bar_countdown">clique para fechar [<span id="add_#MODULO#_status_bar_countdown">5</span>]</div>
			</div>
			*/
			
		}

	} // end widgets object
} // end else statement
//--- end RMwidgets.js ---

//--- start RMjqueryPlugins.js ---

$.fn.redirecionarUrl = function(local) {
	var b = document.getElementsByTagName('base');
	if (b && b[0] && b[0].href)
	{
		if (b[0].href.substr(b[0].href.length-1) == '/' && local.charAt(0) == '/')
			local = local.substr(1);
		local = b[0].href + local;
	}
	window.location = local;
};

$.fn.clearForm = function() {
	return this.each(function(){
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

$.fn.shortUrl = function(settings, callbackFnk){
	var obj = $(this);
	var defaults = {
		login:      'bitlyapidemo',
		apiKey:     'R_0da49e0a9118ff35f52f629d2d71bf07',
		history:    '1',
		format:    'json',
		longUrl:    ''
	};
	
	if (settings){$.extend(defaults, settings);}
	
	var urlData = "http://api.bit.ly/v3/shorten?"
		+"&login="+defaults.login
		+"&apiKey="+defaults.apiKey
		+"&longUrl="+defaults.longUrl
		+"&history="+defaults.history
		+"&format="+defaults.format+"&callback=?";
	
	$.getJSON(urlData, function(retorno){
		// now call a callback function
		if(typeof callbackFnk == 'function'){
		  callbackFnk.call(this, retorno);
		}
		else
		{
			var type = obj.attr('type'), tag = obj.get(0).tagName.toLowerCase();

			if (retorno.status_code == 200 ){
				if (tag == 'input'){
					$(obj).val(retorno.data.url);
				}
				else{ 
					$(obj).append(retorno.data.url);
				}
				//alert(this.retorno.data.url);
				//alert($(this).attr('id'));
			}
			else{
				alert(retorno.status_code);
				//alert(retorno.data.url);
			}
		}
	});
}


//--- end RMjqueryPlugins.js ---
