/** Front end javascript to replace the following:
 * functions-uncomp.js
 * mootools.js
 * ajax.js
 * functions.js
 * showHideDivs.js
 */


/* ================ functions-uncomp.js =================== */
var slides;
var fades = new Array();
var fadeDuration = 1000;
var MODULES_URL = '/includes/modules';
var BASE_IMAGES = MODULES_URL + '/base/images';
var DELIMETER = "_&_";
var mouseX, mouseY;
var headerToolbarButtons = Array();
var ajaxIndication = "&AJAXED=true";

function add_header_toolbar_buttons() {
	var headerToolbar = $('#headerToolbarButtons');
	if (headerToolbar) {
		$.each(headerToolbarButtons, function(key, html) {
			headerToolbar.append(html);
		});
	}
}

function popUp(URL,width,height) {
	var left = (screen.width - width) / 2;
	var top = (screen.height - height) / 2;
	var size = "width=" + width + ", height=" + height +" ,left=" + left + " ,top="+ top;
	insert_window = window.open(URL, 'popup', 'toolbar=0,scrollbars=1,statusbar=0,menubar=0,resizable=1,'+size);
	insert_window.focus();
}

function show_form_errors(form, jsonObj){
	var fields = jsonObj.fields;
	// reset the fields
	for(var i = 0; i < fields.length; i++){
		if($("#field_" + fields[i].field) != undefined){
			$("#field_" + fields[i].field).removeClass('warning');
				// reset the error message
            if($("#message_" + fields[i].field)){
                $("#message_" + fields[i].field).html('');
            }
		}
	}
	
	var errors = jsonObj.errors;
	for(var i = 0; i < errors.length; i++){
		// change style to warning
		if($("#field_" + errors[i].field) != undefined){
			$("#field_" + errors[i].field).addClass('warning');
		}
		// output the error message
		if($("#message_" + errors[i].field)){
			$("#message_" + errors[i].field).html(errors[i].message);
		}
	}
}

String.prototype.reverse = function(){
	splitext = this.split("");
	revertext = splitext.reverse();
	reversed = revertext.join("");
	return reversed;
}

function reveal_email(part1, part2, qstr){
	if(part1 != "" && part2 != ""){
		document.location = 'mailto:' + part2.reverse() + "@" + part1.reverse() + qstr;
	}
}

function showHide(id){
    $('#' + id).toggle();
}

function hideShow(id){
    $('#' + id).toggle();
}

function show_hide_sub_nav(idval, display){
	if(idval != ''){
		var pieces = idval.split('_');
		var num = pieces[1];
		
		if($("#sub_" + num).css("display") != display){
			$("#sub_" + num).css("display", display);
		}
	}
}

function showHideDivs() { //v6.0
	var i,p,v,obj,args=showHideDivs.arguments;
	for (i=0; i < (args.length-1); i+=2) {
		if((obj = document.getElementById(args[i])) != undefined){
			v=args[i+1];
			if (obj.style) { 
				obj=obj.style; 
				v=(v=='show')?'block':(v=='hide')?'none':v; 
			}
			obj.display=v;
		}
	}
}

function get_list_order(theList, attributeName){
	var ar = new Array();
	var children = document.getElementById(theList).childNodes;
	// clear the styles first
	for(i = 0; i < children.length; i++){
		if(children[i].nodeName == "LI"){	// make sure it is a list tag
			if(children[i].getAttribute(attributeName) != null){
				ar.push(children[i].getAttribute(attributeName));
			}
		}
	}
	return ar;	// return the array with the order
}

function get_cookie(cookiename){
	var allcookies = document.cookie;
	var pos = allcookies.indexOf(cookiename + "=");
	if(pos != -1){
		var start = pos + (cookiename.length + 1);
		var end = allcookies.indexOf(";", start);
		if(end == -1){ end = allcookies.length; }
		var value = allcookies.substring(start, end);
		value = unescape(value);
		return value;
		
	}else{
		return false;
	}
}

function set_cookie(name, value, domain, expires){
	var days;
	if(expires == undefined || expires == -1){ 
		days = expires == -1 ? -1 : 1; //default life of cookie, in days
	}else{
		days = expires; //life of cookie, in days
	}
	expires = new Date();
	expires.setTime( expires.getTime() + (days * 1000 * 60 * 60 * 24) );
	
	var str = name + "=" + value +"; path=/; expires=" + expires.toGMTString();
	
	str += ((domain != "" && domain != undefined)  ? "; domain=" + domain : "");

	document.cookie = str;
}

function submit_form(id){
	$(id).submit();
}

function try_text_focus(form, field){
	$("#" + form + " input[name='" + field + "']").focus();
}

// **** TINY MCE FUNCTIONS FOR SIMPLE TEXT AREAS *** //

function load_tinymce(el){
			tinyMCE.init({
				mode : "exact",
				elements : el,
				theme : "advanced",
				skin : "thebigreason",
				convert_urls: false,
				plugins : "style,advhr,advimage,advlink,nonbreaking,paste,save",
				// Theme options
				theme_advanced_buttons1 : "formatselect,bold,italic,removeformat,|,bullist,numlist,|,justifyleft,justifycenter,justifyright,|,pastetext",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",
				theme_advanced_blockformats : "p,h4",
				valid_elements: "p,a[href|target=_blank],strong/b,div[align],br,h3,i,ul,li,ol",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : false
			});
}

function save_tinymce() {
	// broken-out function to tell active editor to save itself
	// could have been put in its primary caller "validate_form_ajax"
	// but the below function causes validate_form_ajax to stop????
	// plus, this way we can use it elsewhere.
	if(typeof tinyMCE !== 'undefined') {
		if(tinyMCE.activeEditor) {
			// does not equal null, so save()
			tinyMCE.activeEditor.save();
		}
	}
}

function CKupdate(){
	if(typeof CKEDITOR !== 'undefined') {
		for ( instance in CKEDITOR.instances )
			CKEDITOR.instances[instance].updateElement();
	}
}


function upper_case_first(text){
	return text.substr(0, 1).toUpperCase() + text.substr(1);
}

function evaluate_js(response){
	//alert("evaluate_js");
	// now find the scripts that are needed
	var startTag = "<script type='text/javascript'>";
	var endTag = "</script>";
	
	var pos = response.indexOf(startTag);

	while(pos > -1){
		var endPos = response.indexOf(endTag, pos + 1);
		if(endPos > -1){
			var start = pos + startTag.length;
			var js = response.substr(start, endPos - start);
			//alert(js)
			eval(js);
			pos = response.indexOf(startTag, endPos);
		}
	}
}

/* ============= ajax.js BASE =================== */

function base_ajax(tagID, url, sendStr, callback) {
	$.ajax({
		url: url,
		type: "POST",
		data: sendStr + ajaxIndication,
		success: function(resp) {
			var response = resp;
			if(tagID != '') {
				$('#' + tagID).html(resp);
			}
			
			if(callback != '' && callback != undefined) {
				eval(callback);
			}
		},
		error: function(resp) {
			////console.log(resp.responseText);
			alert('Request failed');
		}
	});
}

function validate_form_ajax(formID, type) {
    var form = $('#' + formID);
    var formAction = $('#' + formID + ' input[name=formAction]').val();
    $('#' + formID + ' input[name=formAction]').val('validate');
    CKupdate(); // clean up any CKEditor if dirty
	
    if(type === 'custom') {
        url = $('input[name=validateURL]').val();
    } else if(type.indexOf('special_') > -1) {
        var parts = type.split("_");
        url = MODULES_URL + '/' + parts[1] + '/controllers/editInsert.php';
    } else {
        url = $(form).attr('action');
    }

    $.ajax({
        url: url,
        type: "POST",
        data: $(form).serialize(),
        success: function(resp) {
            var errorObj = $.parseJSON(resp);
            
            // reset original form action
            $('#' + formID + ' input[name=formAction]').val(formAction);
            
            if(errorObj && errorObj.errors.length > 0) {
                show_form_errors(form, errorObj);
            } else {
                $(form)[0].submit();
            }
        },
        error: function(resp) {
            alert('Form did not validate');
        }
    });
}

/* ============= functions.js CLIENT_FILES ================ */
function search_clear(){
	var elem = document.getElementById("searchText");
	if(elem.value == "Search"){
		elem.value = "";
	}
}
function search_default(){
	var elem = document.getElementById("searchText");
	if(elem.value == ""){
		elem.value = "Search";
	}
}

/* ============= Front end pod functions =================== */

function pod_accordion_click(headerText,podID){
	if(typeof(pageTracker) != "undefined"){
		var labelText = headerText + " - [" + podID + "]";
		pageTracker._trackEvent("Pod-Accordion", "click", labelText);
	}	
}

