// ***************** AJAX stuff *************************

var ajaxIndication = "&AJAXED=true";

// creates a request object with which the data can be
// "tunneled" through
function create_request(){
    var req;					// the request object that will be created
    // if using a regular complaince standard browser
    if (window.XMLHttpRequest){
        req = new XMLHttpRequest();
    }// if using Internet Explorer
    else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
	
    if (!req) {
        alert('Cannot create an XMLHTTP instance');
        return false;
    }else{
        return req;
    }
}

/* the base ajax calling function
  * usually you want to set up a function that calls this one
  * and supplies it with the parameters for a specific <div>tag you need to work with
  * tagID = the id of the div tag to put HTML into
  * url = the dynamic page waiting for post data, that will return the HTML
  * sendStr = a string of name=value pairs seperated by &s, which get sent to the url page
  * callback = the function that will be called when data is received by the browser
  * show = whether you want to change a hidden div to a visible one
  */
function base_ajax(tagID, url, sendStr, callback){
    var req = create_request();
    //alert("base_ajax("+tagID+", "+url+", "+sendStr+", "+callback+")");
    //alert(url);
    //alert(sendStr);
    if(req){
        req.open("POST", url, true);
        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)
		  */
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                var response = req.responseText;
                //alert(req.responseText);
                if(tagID != ""){
                    var elem = document.getElementById(tagID);
                    if(elem) {
                        elem.innerHTML = response;
                    }
                }else{
                //alert(req.responseText);
                }
				
                //alert(callback)	
                if(callback != "" && callback != undefined){	
                    eval(callback);
                }
            }	
        }
		
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        //req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        req.send(sendStr + ajaxIndication);
    }
}

function test_ajax(tagID, url, sendStr, callback){
    var req = create_request();
    //alert("base_ajax("+tagID+", "+url+", "+sendStr+", "+callback+")");
    //alert(url);
    //alert(sendStr);
    if(req){
        req.open("POST", url, true);
        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)
		  */
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                var response = req.responseText;
                alert(req.responseText);
                if(tagID != ""){
                    var elem = document.getElementById(tagID);
                    elem.innerHTML = response;
                }else{
                //alert(req.responseText);
                }
				
                //alert(callback)	
                if(callback != "" && callback != undefined){	
                    eval(callback);
                }
            }	
        }
		
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        //req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        req.send(sendStr + ajaxIndication);
    }
}


function get_pod_ajax(tagID, url, sendStr, callback){
    var req = create_request();
    //alert(url);
    //alert(sendStr);
    if(req){
        req.open("GET", url + "?" + sendStr + ajaxIndication, true);
        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)
		  */
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                var response = req.responseText;
                ///alert(req.responseText);
                if(tagID != ""){
                    var elem = document.getElementById(tagID);
                    elem.innerHTML = response;
                }else{
                //alert(req.responseText);
                }
				
                //alert(callback)	
                if(callback != "" && callback != undefined){	
                    eval(callback);
                }
            }	
        }
        //say_hi();
        req.setRequestHeader("Content-Type", "text/html; charset=UTF-8");
        req.send(null);
    }
}

function link_form_ajax(formID, type){
    var formEl = $('#' + formID),
    formAction = $('#formAction').val();
		
    $('#formAction').val("validate");
	
    // show the pod saving dialog	
    var req = create_request();
    if(req){
        req.open("POST", controllers[type], true);
        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)	
		  */
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                var response = req.responseText;
				
                $('#formAction').val(formAction);
                if (response.indexOf('{"errors"') !== -1) {
                    var jsonObj = $.parseJSON(response);
                    // if there are errors
                    if(jsonObj.errors.length > 0){
                        show_form_errors(form, jsonObj);
                    }
                } else {
                    base_ajax("", controllers[type], formEl.serialize(), DDM.AssetController.asset_added(response));
                }
            }	
        }
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(formEl.serialize());
    }
}

function page_form_ajax(form){
    // set the pageID
    var pageID = form.pageID.value;

    var req = create_request();
    if(req){
        req.open("POST", controllers["pageEditInsert"], true);
        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)
		  */
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                // response formatted 'pageID url saved [new]'
                var response = req.responseText;
                var parts = response.split(" ");
                //alert(response);
                // if url redirects
                if(form.typeID.value == "2"){
                    window.location.href = "/admin/pages/?navigationID=" + parts[0];
                }
                else{
                    // reload the page content if a page was created
                    //alert('response');
                    if(response.indexOf("new") > -1){
                        window.location.href = "/admin/pages/?url=" + parts[1];
                    /*
						base_ajax(pageContentsDiv, MODULES_URL + "/base/controllers/adminPageContentDisplay.php", "pageID=" + parts[0]);
						base_ajax(listDiv, MODULES_URL + "/base/controllers/adminPagesList.php", "pageID=" + parts[0] + "&url=" + parts[1]);
						*/
                    }
					
                    // if the form was saved
                    else if(response.indexOf("saved") > -1){
                        //refresh_page();
                        window.location.href = "/admin/pages/?url=" + parts[1];
                    /* -- TW -- 02/8/08 9:32 AM -- changed so that when changing template type, it reflects the accurate stuff below
						podManager.hide_status_bar("contents");
						show_page_basics(pageID);
						var parts = response.split(" ");
						base_ajax(listDiv, controllers["pageList"], "pageID=" + parts[0] + "&url=" + parts[1]);
						// base_ajax("pageAllContent", controllers["pageAllContent"], "pageID=" + parts[0] + "&url=" + parts[1],"podManager = new PodEditManager();");
						// change to saying that the page was saved, then fade out
						*/
                    }else{
                        alert("Oops, form was not saved, try again.");
                    }
                }
            }	
        }
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send($(form).serialize());
    }
}

function pod_form_ajax(form, refreshForm){
    // show the pod saving dialog
    //alert(form.name);
    //alert(form.formAction.value);
	
    toggle_pod_edit_mode("HTML");
    var form = $(form)[0];
	
    var podID = form.podID.value;
    podID = (podID != "" && podID != 0 && podID != undefined ? podID : "New");
	
    var typeID = form.typeID.value;	
	
    if(typeof(typeID) == 'undefined'){
        typeID = $("#podTypeID").val();
    }
	
    //alert("formAction=" + form.formAction.value);
    //alert(controllersPath + "/pods/" + podControllers[typeID]);
    var req = create_request();
    if(req){
        //alert(controllersPath + "/pods/" + podControllers[typeID]);
        req.open("POST", controllersPath + "/pods/" + podControllers[typeID], true);
        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)
		  */
        req.onreadystatechange = function(){
            if (req.readyState == 4 && req.status == 200) {
                // response formatted 'pageID saved [new]'
                var response = req.responseText;
                var parts = response.split(" ");
                podID = parts[0];
                //alert(podID);
                var isNew = (response.indexOf("new") > -1 ? true : false);
				
                // if the form was saved
                if(response.indexOf("saved") > -1){
                    // if refresh form, get fresh form
                    if(refreshForm){
                        /* -- TW -- 01/14/08 11:15 AM -- trying to do save changes, with asset add
						if(isNew == true){
							edit_pod("New_" + podID, typeID, "saved");
						}else{
							edit_pod(podID, typeID, "saved");
						}			
						*/
                        if(isNew == true){
                            $("#pod_New").attr('id', "pod_" + podID);
                            $("#podContents_New").attr('id', "podContents_" + podID);
                            $("#podNameNew").attr('id', "podName" + podID);
                            form.podID = podID;
                            podManager.id_status_bar(podID);
                        }
                        edit_pod(podID, typeID, "saved");
                    }else{
                        // replace the form with the display
                        //show_pod_basics(podID);
                        var url = window.location.href;
                        url = url.split("#");
                        url = url[0];
                        //alert(url);
                        //window.location.href = url;
                        if(typeID == 3){
                            parent.refresh_page();
                        }else{
                            window.location = url + "#podName" + podID;
                            refresh_page();
                        }
                    }

                // change to saing that the page was saved, then fade out

                }else{
                    alert("Oops, form was not saved, try again.");
                //alert(response);
                }
            }	
        }
				
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        var temp = $("#podForm" + podID).serialize().split("&");
		
        //alert(temp.join("\n"));
        //alert($("podForm" + podID).bodyText.value);
		
        var sendStr = (refreshForm == true ? "&submitMethod=saveChanges" : "");
        req.send($("#podForm" + podID).serialize() + sendStr);
    //req.send("formAction=update&bodyText=" + $("podForm" + podID).bodyText.value);
    }
}

function validate_form_ajax(form, type){
    var req = create_request();
    var ignoreErrors = 0;
    if(form.formAction.value=="delete"){
            
        ignoreErrors = 1;
        
    }
    var formAction = form.formAction.value;
        form.formAction.value = "validate";
    var formID;
	
    // clean up TinyMCE if dirty and if
    // there is a tinymce editor somewhere in teh DOM
    save_tinymce();
	
    // clean up CKEditor if dirty and
    // if there is an editor in the DOM
    if(typeof CKEDITOR !== 'undefined') {
        for ( instance in CKEDITOR.instances )
            CKEDITOR.instances[instance].updateElement();
    }

    //alert(form.formAction.value);
    if(req){
        if(type == "page"){
            url = controllers["pageEditInsert"];
            formID = "pageForm";
        }
        else if(type.indexOf("Links") > -1){
            url = controllers[type];
            formID = "assetForm";
        }
        else if(type.indexOf("special_") > -1){
            var parts = type.split("_");
            url = MODULES_URL + "/" + parts[1] + "/controllers/editInsert.php";
            formID = "specialForm";
        }
        else if(type.indexOf("base_") > -1){
            var parts = type.split("_");
            url = MODULES_URL + "/base/controllers/" + parts[1] + "/editInsert.php";
            formID = "specialForm";
        }
        else if(type == "custom"){
            url = form.validateURL.value;
            formID = form.id;
        //formID = "specialForm";
        }
        // 
        else{
            formID = "assetForm";
            url = form.formController.value;
        }

        //alert("url ("+url+")");
        // open the connection
        req.open("POST", url, true);

        /* when the data has been completely loaded back into the browser
		  * and the status is OK, it puts the text string that was returned
		  * into the tag specified in curDiv, and shows the div (if specified)
		  */
		req.onreadystatechange = function(){
			if (req.readyState == 4 && req.status == 200) {
				//alert("got response");
				var response = req.responseText;
				
				form.formAction.value = formAction;
				
                //alert("before Json");
                var errorObj = $.parseJSON(response);
                //alert("after Json");
				
                //alert(Json.toString(errorObj));
                // if there are errors
                if(errorObj.errors.length > 0 && ignoreErrors != 1){
                    show_form_errors(form, errorObj);
                }
                else if(response.indexOf('{"errors"') > -1  || ignoreErrors == 1){
					
                    // call the correct form submitions based on the type
                    if(type == "page"){
                        page_form_ajax(form);
                    }
                    else if(type == "moduleFunction"){
                    // not handled yet, going with default values if fields are "required"
                    }
                    else if(type.indexOf("Links") > -1){
                        links_form_ajax(form, type);
                    }
                    else{
                        //alert("form.submit")
                        //if (console && console.log) console.log('form.submit');
                        form.submit();
                    }
                }
                else{
                    alert("Form did not validate");
                //alert(response);
                }
            }	
        }
        req.setRequestHeader('User-Agent','XMLHTTP/1.0');
        // set the header
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        var str = "";
		
        /* if(form.file != undefined){
			str = "&file=" + form.file.value
		} */
		
        //collect any files
        if(form.elements != undefined){
            for (var key in form.elements){
                if (form.elements[key] != undefined && form.elements[key].type == 'file' && form.elements[key].value){
                    str += "&"+form.elements[key].name+"="+form.elements[key].value;
                }
            }
        }
        // get the form values string
        qString = $(form).serialize();

        // send the request
        //alert(qString + "; str = " + str);
        req.send(qString + str);
    }
}

