/**
 * ====================================
 *                 AJAX
 * ====================================
 * 
 * The system will have 2 types of messaging displays:
 * 
 * For normal submits and form loads, the usual message to display is in the template
 * using the standard $messages array in the Controller
 * 
 * 		application/classes/controller/base.php ($messages array)
 *     	application/views/template/div/messages.php => structure ($messages array)
 * 
 * For ajax submits (JQuery Form and Xajax), we will utilize the upper right hand
 * corner to display messages in an unobtrusive manner and without messing up majority
 * of the layouts by pushing entire DIVs down 
 *  
 *    	JQuery Form
 *  
 *     		application/classes/controller/base.php 
 *     		application/classes
 * 
 *   	Xajax 
 *     
 *    		application/classes/controller/base.php (loads up template/div/ajax)
 *    		application/views/template/div/ajax.php 
 *             (this div gets loaded whenever there is an ajax function added to the controller)
 * 	           (pumps out the default callback and xajax functions)
 *             (sets the default global callback)
 *          velocimedia/classes/xajax/response/plugin.php ($messages array)
 *             FIX (cleanup scripts binds the $message array to generate javascript calls)
 *             FIX Just pass the $message array back to javascript to deal with???
 *             Something like $response->call();
 *             
 * On the messages to be displayed (coming back from somewhere) - passed into javascript function
 * Since we can only display one background, we will do the following:
 * 
 * 		If all messages are of type="success" => background is green
 * 		Otherwise, background will red 
 * 		TODO: Maybe we can make it the highest severity (for example: if warning, still display yellow)
 *       
 */

/**
 * This should be called when instantiating any ajax calls to display
 * to the user a "loading" status panel on upper right
 * 
 * For xajax: 
 * 
 * 		This is already bound for any xajax_* function calls using the global callback
 * 
 * For jquery form plugin: 
 * 
 *      This needs to be put into the beforeSubmit
 * 
 * 		$(document).ready(function(){
 *			$('#<?php echo $tab ?>Form').validate({
 *       		submitHandler: function(form) {
 *           		$(form).ajaxSubmit({
 *               		beforeSubmit: showLoadingMessage,
 *               		success: showResponseMessages,
 *           		});
 *       		}
 *   		});
 * 		});
 *  
 */

var FIELD_PREFIX = "field-";
var TR_PREFIX    = "tr-";
var TD_PREFIX    = "td-";
var TH_PREFIX    = "th-";
var TABLE_PREFIX = "table-";
var DIV_PREFIX   = "div-";

function hideLoadingMessage() {
	$.jN.close(); 
}

function showLoadingMessage(message)
{
	var html = '<img src="/media/img/ajax-loader.gif" style="vertical-align:middle"/> ';
	if( message ) {
		html += message;
	} else {
		html += "Loading ...";
	}
	$.jN(html, { 
	    margin:0, 
	    width:200, 
	    effect:'fade', 
	    padding:10, 
	    align:'right', 
	    position:'top', 
	    close:false, 
	    timeout:0,
	    opacity:0.4,
	    background:'#808080'
	});
}

/**
 * This is what the Xajax routines call
 * @param messages
 * @return
 */
function showMessagesFromObject(messages)
{
	var messageArr = new Array();
	if( messages.error )
	{
		messageArr['error'] = new Array();
		for( var ii=0; ii<messages.error.length; ii++)
		{
			messageArr['error'].push(messages.error[ii]);
		}
	}
	if( messages.success )
	{
		messageArr['success'] = new Array();
		for( var ii=0; ii<messages.success.length; ii++)
		{
			messageArr['success'].push(messages.success[ii]);
		}
	}
	if( messages.notice )
	{
		messageArr['notice'] = new Array();
		for( var ii=0; ii<messages.notice.length; ii++)
		{
			messageArr['notice'].push(messages.notice[ii]);
		}
	}
	if( messages.warning )
	{
		messageArr['warning'] = new Array();
		for( var ii=0; ii<messages.warning.length; ii++)
		{
			messageArr['warning'].push(messages.warning[ii]);
		}
	}
	showMessages(messageArr);
}

/**
 * This is what the form plugin will call
 */
function showResponseMessages(messages)
{
	var obj = $.parseJSON(messages);
	showMessagesFromObject(obj);
}

/**
 * Main show message routine to display various messages passed to this function
 * 
 * This should be fairly resilient where it will try to NOT display messages that are empty
 * @param messages
 * @return
 */
function showMessages(messages)
{
	// Only do stuff if there are messages passed in
	if( messages instanceof Array )
	{
		var background = "#E6EFC2";
		var timeout = 60000;
		var html = "";
		var errorArr;
		var successArr;
		var noticeArr;
		var warningArr;
		if( messages['error'] && $.trim(messages['error'].toString())!="" )
		{
			html += '<li class="error">' + messages['error'].join('</li><li class="error">') + "</li>";
			background ="#FBE3E4";
		}
		if( messages['warning'] && $.trim(messages['warning'].toString())!="" )
		{
			html += '<li class="warning">' + messages['warning'].join('</li><li class="warning">') + "</li>";
		}
		if( messages['notice'] && $.trim(messages['notice'].toString())!="" )
		{
			html += '<li class="notice">' + messages['notice'].join('</li><li class="notice">') + "</li>";
		}
		if( messages['success'] && $.trim(messages['success'].toString())!="" )
		{
			html += '<li class="success">' + messages['success'].join('</li><li class="success">') + "</li>";
		}
		// Trim the HTML
		html = $.trim(html);
		if( html!="" )
		{
			if( html.length>500 ) timeout = (html.length*12);
			$.jN('<div id="div-panel-ajax" class="message">' + html + "</div>", { 
				    margin:0, 
				    width:400, 
				    effect:'fade', 
				    padding:10, 
				    align:'right', 
				    position:'top', 
				    close:false, 
				    opacity:0.9,
				    //timeout:0,
				    timeout:timeout,
				    background:background
				});
		}
		else
		{
			$.jN.close(); 
		}
	}
	else
	{
		$.jN.close(); 
	}
}

function showAlert(message) {
	var messageArr = new Array();
	messageArr['error'] = new Array();
	messageArr['error'].push(message);
	showMessages(messageArr);
}

function refreshTab(divName, index) {
	if( typeof divName == 'undefined' ) {
		divName = 'div-panel-tabs';
    }
	if( typeof index == 'undefined' ) {
		index = $("#" + divName).tabs("option", "selected");
	}
	$("#" + divName).tabs("load",index); 
}

function addOption(id, text, value)
{
	$('#' + FIELD_PREFIX + id).append($('<option></option>').val(value).html(text));
}

function addOptions(id, options)
{
	if( options )
	{
		for( var key in options ) 
		{
			addOption(id, options[key], key);
		}
	}
}

function clearOptions(id)
{
	$('#' + FIELD_PREFIX + id + ' >option').remove();
}

function dump(obj) 
{
	var output = "";
	if( obj )
	{
		for( var key in obj ) 
		{
			output += key + "=" + obj[key] + "\n";
		}
	}
	console.log(output);
	//alert(output);
}

// Validator additional functions

$(document).ready(function() {
    $.validator.addMethod("phoneUS", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, ""); 
        return this.optional(element) || phone_number.length > 9 &&
            (phone_number.match(/^\d{3}\-\d{3}\-\d{4}?\s*-?\s*[Xx]\d{1,5}$/) || 
             phone_number.match(/^\d{3}\-\d{3}\-\d{4}$/));
    }, "Please specify a valid phone number");
    // Add credit card expire validator
    $.validator.addMethod("creditCardExpiryDate", function(value, element, params) {
        var minMonth = new Date().getMonth() + 1;
        var minYear = new Date().getFullYear();
        var $month = $(params.month);
        var $year = $(params.year);
        if( $month.val()!='' && $year.val()!='' ) {
            var month = parseInt($month.val(), 10);
            var year = parseInt($year.val(), 10);
            if ((year > minYear) || ((year === minYear) && (month >= minMonth))) {
                return true;
            } else {
                return false;
            }
        } 
        return true;
    }, "Credit Card is already expired.");
});
