/** 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 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 submit_form(id){
	$(id).submit();
}

// **** 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);
}

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

function base_ajax(tagID, url, sendStr, callback) {
    $.ajax({
        url: url,
        type: "POST",
        data: sendStr + ajaxIndication,
        success: function(resp) {
            if(tagID != '') {
                $('#' + tagID).html(resp);
            }
            
            if(callback != '' && callback != undefined) {
                eval(callback);
            }
        },
        error: function(resp) {
            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
            $('input[name=formAction]').val(formAction);
            
            if(errorObj.errors.length > 0) {
                show_form_errors(form, errorObj);
            } else {
                $(form).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);
	}	
}

