/**
 * JFramework 
 * 
 * @version 1.2
 */
JFramework=function() {
	this.Toaster;
	this.basket;
	this.target;
	this.wizardHelper;
	this.redirect;
	this.loading;
	
	/**
	 * Put a default action to forms.
	 */
	this.init=function() {
		// Get the Focus to the search tool
		this.basket=new GBBasket();
		this.basket.init();	
		this.loading="<div class='row' style='text-align:center; padding:20px;'><img src='/designs/basic/images/pageloading.gif' align='center'><br/>Loading please wait...</div>";
		
		var elms;
		// Find form elements and add default actions
		try {
		elms = document.getElementsByTagName('form');
		} catch(e) {
		}
		for(i=0;i<elms.length;i++) {
			
		    var options = { 
		        target:        '#mainBlock',   // target element(s) to be updated with server response 
		        beforeSubmit:  this.validate,  // pre-submit callback 
		        success:       this.processForm // post-submit callback 
		 
		        // other available options: 
		        //url:       url         // override for form's 'action' attribute 
		        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
		        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
		        //clearForm: true        // clear all form fields after successful submit 
		        //resetForm: true        // reset the form after successful submit 
		 
		        // $.ajax options can be used here too, for example: 
		        //timeout:   3000 
		    }; 
		 
		    // Check if we have passed a target
		    if( elms[i].getAttribute("target") != undefined && elms[i].getAttribute("target") != ""  ) {
		    	options.target='#' + elms[i].getAttribute("target");
		    }
		    
		    // Sometimes we have set a daft target within the form. In this case lets set it back to the default.
		    if(options.target=="#" || $(options.target).lenght==0) {
		    	this.target="#mainBlock";
		    } else {
		    	this.target=options.target;
		    }
		    
		    // Check if the form refreshed the browser or uses ajax to load the data into the main block	
		    if( elms[i].getAttribute("redirect") == "true" ) {
		    	this.redirect=true;
		    	$('#' + elms[i].name).submit(this.validate);
		    } else {
		    	this.redirect=false;
		    	$('#' + elms[i].name).ajaxForm(options);
		    }
		}
		
		// Loop over the input items and add validation code where required
		// TODO: Build up validation logic
		elms = document.getElementsByTagName('input');
		for(i=0;i<elms.length;i++) {
			if( elms[i].getAttribute("type") == "text" ) {
				// Validate Text items
				elms[i].onkeyup=this.validateItem;
			}
		}
		
		myFramework.enableButtons();
	}
	
	this.loadURL=function(url,target) {
		
		// If there is a form to proccess then go and get the data
		myFramework.target = target;
		myFramework.target.html(this.loading);
		
		$.ajax({
			type: "POST",
			url: url,
			success: function(s) {
				//target[0].innerHTML="";
				setTimeout(function(){
					target.hide();
					myFramework.target.html("");
					target.append(s);
					target.slideDown();
					myFramework.init();
					},1500);
			}
		});
	}
	
	this.loadModule=function(module,method,target,arguments) {
		// If there is a form to proccess then go and get the data
		if( arguments == undefined) {
			arguments = "";
		} else {
			arguments = "&" + arguments;
		}
		
		// If there is a form to proccess then go and get the data
		myFramework.target = target;
		$(myFramework.target).hide();
		
		$.ajax({
			type: "POST",
			url: "/gateway.php?format=json&action=" + module + "." + method + arguments,
			success: function(s) {
				//target[0].innerHTML="";
				setTimeout(function(){
					target.hide();
					target.html("");
					target.append(s);
					target.slideDown();
					myFramework.init();
					},1500);
			}
		});
	}
	
	this.processForm=function(responseText, statusText) {
		//$('#mainBlock')[0].innerHTML=""
		$(myFramework.target).innerHTML="Loading Please Wait...";
		
		setTimeout(function(){
			$(myFramework.target).innerHTML=responseText;
			$(myFramework.target).slideDown('slow');
 			myFramework.init();
		},2500);
	}
	
	this.validate=function(formData, jqForm, options) {
		var status;
		var msg;
		msg ="";
		
		status=true;
		
		if(formData.length===undefined) {
			formData = this.elements;
		}
		
		msg = "The following values need correcting\n";
		
	    for (var i=0; i < formData.length; i++) {
	    	errmsg = "";
	    	
	    	// Lookup the ID and grab the attribute
	    	// It's not avail here as jform does not pass this data as I made it up :)
	    	if(formData[i].name != "" && formData[i].name != undefined) {
		    	if( $('#'+formData[i].name).attr("required") == "true" ) {
			        if (!formData[i].value) {

			        	var displayname = $('#'+formData[i].name).attr("displayname");
			        	if( displayname==undefined || displayname == "") {
			        		displayname = formData[i].name;
			        	}
			            msg = msg + displayname + '\n';
			            
			            errmsg = displayname;
			            
			            // Focus on the item and set background colour
			            $('#'+formData[i].name).focus();
			            $('#'+formData[i].name).css("background-color","#CCCCCC");
			            status = false;
			        }else {
			        	errmsg = "";
			        }
		    	}
		    	
		    	// Update the error message
	            errorelement = $('#'+formData[i].name).attr("name") + "error";
	            errorelement = $('#' + errorelement );

		        $('#'+formData[i].name).css("background-color","#FFFFFF");	            	
	            errorelement.attr("innerHTML", "* " + errmsg);		    	
		    	
	    	}
	    }
	    
	    if(status==true) {
	    	// We have validated the info so we can set a loading message and send off the AJAX call.
	    	
			// If we wipe out this form them their is nothing for the browser to post over, plus when we are redirecting (refreshing) 
			// the browser this is pointless. 
			if($('#' + this.id ).attr("redirect")!="true") {
				$(this.target).html("<div class='row' style='text-align:center; padding:20px;'><img src='/designs/basic/images/pageloading.gif' align='center'><br/>Loading please wait...</div>");
			}

	    	return status;
	    } else {
//	    	alert( msg);
	    	$(this.target).slideDown('slow');
	    	myFramework.enableButtons();
	    	return false;
	    }
	}
	
	this.validateItem=function() {
		//$('#'+formData[i].name).css("background-color","#FFFFFF");
		if(this.value == "1" ) {
			$('#'+this.name).css("background-color","#CCCCCC");
		} else {
			$('#'+this.name).css("background-color","#FFFFFF");
		}
	}
	
	this.disableButtons=function() {
		$(":submit").attr("disabled",true);
		$(":button").attr("disabled",true);
		$(":input").attr("disabled",true);
	}
	
	this.enableButtons=function() {
		setTimeout(function(){
			$(":submit").attr("disabled",false);
			$(":button").attr("disabled",false);
			$(":input").attr("disabled",false);
			$('#currentltv').attr("disabled",true);
			},2000);	
	}

	/**
	 * Create a bookmark that links to the given page. Listed under the title.
	 */
	this.CreateBookmarkLink=function(title, url) {
		if(title==undefined) {
			title = document.title;
		}
		if(url==undefined) {
			url = window.location.href;
		}

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( url, title);
		} else if(window.opera && window.print) { // Opera Hotlist
			return true; 
		}
	}
	
	this.quickContentUpdate=function(itemid,target) {
	    var args = "&itemid="+itemid+"&format=json";

		$.ajax({
			type: "POST",
			url: "/gateway.php?format=json&action=cms.loadPageContent" + args,
			success: function(s) {
				$('#'+target).html(s);
			}
		});

		// Make this recursive ever 2 seconds
		setTimeout(function(){
			myFramework.quickContentUpdate(itemid,target);
			},3000);
	}
	
    /**
     * Converts a form to JSON data, perfect when using $.post to send ajax data
     */
    this.form2jsonOld=function(form) {
        if($('#' + form).length==0) {
            return "{}";
        }
       
        var json = "{";
        jQuery.each($('#' + form).ajaxForm()[0].elements, function(item) {
        if($('#' + form).ajaxForm()[0].elements[item].id != "") {
        json = json + "\"" + $('#' + form).ajaxForm()[0].elements[item].id + "\"";
        json = json + ":";
        json = json + "\"" + $('#' + form).ajaxForm()[0].elements[item].value + "\"";
        if($('#' + form).ajaxForm()[0].elements[item+1] != undefined) { 
        	json = json + ",";
        }}});

        // {"status":"success","data":"<h1>Hello<\/h1>","msg":"The data was saved successfully"}
        json = json + "}";
        var json = eval('(' + json + ')');
        return json;   
    }
    
    this.form2json=function(form) {
        if ($("#" + form).length == 0) {
            return "{}";
        }
        var json = "{";
        jQuery.each($("#" + form).ajaxForm()[0].elements, function (item) {
        	if ($("#" + form).ajaxForm()[0].elements[item].id != "") {
        		json = json + "\"" + $("#" + form).ajaxForm()[0].elements[item].id + "\"";
        		json = json + ":";json = json + "\"" + $("#" + form).ajaxForm()[0].elements[item].value + "\"";
        		if ($("#" + form).ajaxForm()[0].elements[item + 1] != undefined) {
        			if ($("#" + form).ajaxForm()[0].elements[item + 1].id != "") {
        				json = json + ",";
        			}
        		}
        	}
        });
        
        json = json + "}";
        var json = eval("(" + json + ")");
        return json;
    }
    
    /**
     * Clears all the elements belonging to the given form
     */
    this.clearform=function(ele) {
        $(ele).find(':input').each(function() {
            switch(this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });

    }

}