/* JAVASCRIPT UTILITY METHODS
   Karol Golka
   May 12, 2007
   http://webstruments.com   
*******************************/

//// GLOBALS
//String.prototype.trim = 
//function () {
//    return this.replace(/^\s*|\s*$/,"");
//} 

/* CurrentNav
--------------------------- */
function CurrentNav(nav)
{
    $(nav).addClassName('current');
}



//// Ajax loading indicator
//function loading() {
//    ($('divLoading')) ? $('divLoading').toggle() : void(0); }


/* Grab Form - Generic Form => XML method (DOESN'T HAVE TO BE A FORM)
--------------------------------------------------------------------------------- */
function GrabForm(formname)
{
    // grab 'form' container (doesn't have to be an actual form)
    var myForm = $(formname).descendants();
    
    // BEGIN BUILDING XML
    formXML = Builder.node('form');	
	
    // loop thru form inputs, switch, and build XML
    for(var i=0; i<myForm.length; i++) {
        
        // get element
	    ele = myForm[i];
	    
	    // debug
	    //alert(ele);
	    
	    // switch and build
	    switch(ele.tagName.toLowerCase()) {
		    case "hidden":
		        // build form element XML
        	    formXML.appendChild(Builder.node(ele.name, ele.value));
        	    break;
		    case "button":
			    break;
		    case "textarea":
		        
		        // Is this a CKEDITOR?
		        try {
                    // get that shit
		            formXML.appendChild(Builder.node(ele.name, CKEDITOR.instances[ele.name].getData()));
		            
//		            var o=CKEDITOR.instances[ele.name];
//                    if (o) o.destroy();
//                    
//		            // hide the real textarea so no flicker...
//		            $(ele.name).hide();
		            
		        }
		        catch (err) {
		            // alert('got textarea saveform() error');
		            // OTHERWISE, get value as normal textarea
		            // build form element XML
		            formXML.appendChild(Builder.node(ele.name, ele.value));
		        }
			    break;
		    case "select":
		        // build form element XML
        	    formXML.appendChild(Builder.node(ele.name, $F(ele.name)));
			    break;	
		    case "input":
		        switch(ele.type) {
				    case "text":
				    case "hidden":
				    case "password":
				        // build form element XML
        	            formXML.appendChild(Builder.node(ele.name, $F(ele.name)));
			            break;	
				    case "checkbox":
				        // check if "checked"
				        if (ele.checked)
					        // build form element XML
        	                formXML.appendChild(Builder.node(ele.name, ele.value));
					    break;
				    case "radio":
				        // check if "checked"
				        if (ele.checked)
					        // build form element XML
        	                formXML.appendChild(Builder.node(ele.name, ele.value));
					    break;
				    default:
					    break;
			    } // end switch
				
			    break;
		    default:
			    break;
	    } // end switch
    } // end for loop
	
    // finish xml
    var xml = '<form>' + tagsToUpperCase(formXML.innerHTML) + '</form>';
	
    // debug
    //$('debug').style.display = 'block';
    //$('debug').value = xml; // innerHTML works for FireFox but not IE
    //alert(xml);
    
    // ajax
    return xml;	    	

} // end GrabForm()


/* Save Form
--------------------------------------------------------------------------------- */
function SaveForm(myForm, entity, proc)
{	
    // debugger;
    
    // VALIDATE (but not for Villas)
    // CUSTOM PROCESSING (for villa file uploading, for example):
    if (entity == 'Villa')
        var validationResult = true;
    else
    { 
        // proceed normally           
        var valForm = new Validation(myForm, {useTitles:true});    
        var validationResult = valForm.validate();
    }    
    
    if	(validationResult)
	{
	    // loading
		// loading();
		
		// grab form
		var xml = GrabForm(myForm);
		
		// make the ajax call
		new Ajax.Request('../../ajax/base/base-ajax-processor.aspx', {
            parameters: { xml : xml, entity : entity, proc : proc},
            onSuccess: function(transport) {

                // grab what we need
                var res = transport.responseText;

                // loading
		        // loading();
		        
		        // alert('Great Success!');
		        try {
                // destroy any ckeditors
                $$('textarea').each(function(s){
                    var o=CKEDITOR.instances[s.id];
                    if (o) o.destroy();            
                });
                } catch(e) { alert(e.description);}
            
		        
		        // close modal control
		        HideFacebox();
		        
		        // Reload Entity List
		        List(entity);
		        
		        // scroll to top
		        new Effect.ScrollTo('header');

            },
            onFailure: function(transport) {
                alert("There was an error!");
                $('tarDebug').update(transport.responseText);
                
                // enable save button for villas
                if (entity == 'Villa')
                {
                    $('btnSave').update('Save');
                    $('btnSave').disabled = false;
                }
            }
        });   
		
   }
}




/* List
--------------------------------------------------------------------------------- */
function List(entity)
{	
	/*
	alert(' ### DONE ### 1. (ASPX/HTML) <script> element at bottom of articls.aspx calls JS:List("Articles")\r\n'+
	'### DONE ### 2. (JS) That makes a new AJAX request to base-ajax-processor.aspx\r\n\r\n'+
	'### DONE ### 3. (C# LOCALHOST + C# DATAACCESSTIER) Processor calls DataAccessTier List() method which calls procListArticles\r\n\r\n'+
	'### DONE ### 4. (SQL) procList will return all Articles in XML format (as a string)\r\n\r\n'+
	'### DONE ### 5. (C# / XSLT) XML articles transformed via XSLT into an HTML snippet and returned to AJAX\r\n\r\n' +
	'### DONE ### 6. (JS) Javascript grabs that returnvalue (responseText)\r\n\r\n' +
	'### DONE ### 7. (ASPX/HTML) That responseText is loaded dynamically into some DIV on the page');
	*/
	
	// make the ajax call
	new Ajax.Request('../../ajax/base/base-ajax-processor.aspx', {
        parameters: { entity : entity, proc : 'List' },
        onSuccess: function(transport) {

            // grab what we need
            var res = transport.responseText;
	        
	        // dynamically inject into our DIV
	        $('divList'+entity+'s').update(res); 
	        
	        // load faceboxes
	        var f = new Facebox();
	        
        },
        onFailure: function(transport) {
            alert("There was an error!");
            $('tarDebug').update(transport.responseText);
        }
    });  	
}

/* Delete
--------------------------- 
SS: This function will delete entity and refresh list of entities
*/
function Delete(entity, id)
{
    //just to be sure
    if (confirm("Are you sure you want to delete this record? \r\n\r\n This action is permanent!")) {
        
        // make the ajax call
	    new Ajax.Request('../../ajax/base/base-ajax-processor.aspx', {
            parameters: { entity : entity , id : id , proc : 'Delete' },
            onSuccess: function(transport) {
                
                //we made it
                // alert( entity + " id=" + id + " was sucesfully deleted!");
                
                //ajax refresh    
                List(entity);
            },
            onFailure: function(transport) {
                alert("There was an error!");
                $('tarDebug').update(transport.responseText);
            }
        });
    }
}



/* Get URL Parameter
--------------------------- */
function gup( name )
{
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}

/* URL decode / encode
--------------------------- */
function urldecode(text) {

    text= text.replace(/\%2f/g,"/");
    text= text.replace(/\%3f/g,"\\");
    text= text.replace(/\%3d/g,"=");
    text= text.replace(/\%26/g,"&");
    return text;
}
function urlencode(text) {

    text= text.replace(/\//g,"%2f");
    text= text.replace(/\?/g,"%3f");
    text=  text.replace(/=/g,"%3d");
    text=   text.replace(/&/g,"%26");
    text=   text.replace(/ /g,"%20");
    return text;
}

/* EscapeTextareas
--------------------------- */
function EscapeTextareas() {
	 
	// grab all textareas
	$('myForm').getElementsBySelector('textarea').each(function(t){
		// replace <br /> with \r\n
		t.value = t.value.replace(new RegExp("<br />", "g"), "\r\n");
	});
	
}


/* ConfirmClose
--------------------------- */
function ConfirmClose()
{
    if (confirm("Are you sure you want to exit? \r\n\r\n Any unsaved changes will be lost!"))
    {
        try {
        // destroy any ckeditors
        $$('textarea').each(function(s){
            var o=CKEDITOR.instances[s.id];
            if (o) o.destroy();            
        });
        } catch(e) { alert('couldnt destroy some ckeditor');}
    
        // close modal 
        HideFacebox(); 
    }
}


function tagsToUpperCase(html)
{
    html = html.replace(/([a-z])s*(=)s*("|')/gi, '$1$2$3');
    if (parts = html.match(/(<\/?[a-z][a-z0-9]*| [a-z]+=)/gi))
    {
        for (var i = 0; i < parts.length; i++)
        {
            var part = parts[i];
            html = html.replace(new RegExp(part, 'g'), part.toUpperCase());
        };
    };
    return html;
}

/* Modalize
--------------------------- */
function modalize(ele, url)
{
    // custom width?
    var width = 900;
    if (arguments[2])
        width = arguments[2];
        
    // make control
    m = new Control.Modal(
        url,
        {
        className: 'modal',     
        closeOnClick: false,
        overlayOpacity: 0.8,
        width: width,
        fade: true,
        iframe: false,
        fadeDuration: .25,
        remoteContentLoaded: setTimeout('new Effect.ScrollTo("myForm", {offset:-20})', 3300)           
    });
    m.open();
    
}


/* HideFacebox
--------------------------------------------------------------------------------- */
function HideFacebox() {
    $('facebox').hide();
    $('facebox_overlay').hide();
}
