/*
 * Enigma CMS plugin
 */
 
jQuery.extend({
      
    CMS_Acquire: function(inURL, inTarget, inRequest, inCleanser, inPreProcessor, inPostProcessor) {
    	//console.info("CMS_Acquire('" + inURL + "', ..., '" + inRequest + "', ..., ..., ...)"); //debug
        /**
         * Get page content
         */
         // Set variable defaults
         var curURL = (inURL == null) ? "" : inURL;
         var curTarget = (inTarget == null || inTarget == "") ? "#bodyContainer" : inTarget;
         var curRequest = (inRequest == null || inRequest == "") ? "" : inRequest; 
         var curCleanser = (inCleanser == null || inCleanser == "") ? "" : inCleanser;
         var curPreProcessor = (inPreProcessor == null || inPreProcessor == "") ? "" : inPreProcessor;
         var curPostProcessor = (inPostProcessor == null || inPostProcessor == "") ? "" : inPostProcessor;


				 //$(document).scrollTop(0); //scroll back to the top of the page
         //Second, if url is defined, build form for get request
         if ((curURL != "")&&(curTarget != "")) {
            $.ajax({
               type: "get",
               url: curURL,
               data: curRequest,
               dataType: "text",
               beforeSend: function() {
                                //$.UI_ShowWaitSmall(curTarget);  // Display loading graphic
                                if(curPreProcessor != "")       // Execute Pre-processor
                                    eval(curPreProcessor);
                            },
               success: function(curResponse) {
               						 if ( typeof $.CMS_ReadResponse != 'function' )
               						 	 return false;
                           tempContent = $.CMS_ReadResponse(curResponse);               // Check response for an error message
                           tempContent = $.CMS_Cleanser(tempContent, curCleanser);      // Cleanup text...remove styles and such
                           $(curTarget).html(tempContent);                              // Move clean content to destination
               						 //$.CMS_RewriteLinks('#contentMain');
                           //alert($(curTarget).html());                                // Visually verify html code
                           $.CMS_Integrator(curTarget);                                 // Replace link/form destinations
                           if(curPostProcessor != "")                                   // Execute Post processor
                               	eval(curPostProcessor);
                               //$.CMS_HistoryApply();
                         },
                failure: function () {
                           this.CMS_ShowError(curTarget);
                         }
            });
        }
        else {
            $.UI_Alert('Sorry, there is a problem with this page. Our team is looking into the issue');
        } 
        return false;
    },
    
    CMS_Acquire_1: function(inURL, inTarget, inRequest, inCleanser, inPreProcessor, inPostProcessor) {
    	//console.info("CMS_Acquire('" + inURL + "', ..., '" + inRequest + "', ..., ..., ...)"); //debug
        /**
         * Get page content
         */
         // Set variable defaults
         var curURL = (inURL == null) ? "" : inURL;
         var curTarget = (inTarget == null || inTarget == "") ? "#bodyContainer" : inTarget;
         var curRequest = (inRequest == null || inRequest == "") ? "" : inRequest; 
         var curCleanser = (inCleanser == null || inCleanser == "") ? "" : inCleanser;
         var curPreProcessor = (inPreProcessor == null || inPreProcessor == "") ? "" : inPreProcessor;
         var curPostProcessor = (inPostProcessor == null || inPostProcessor == "") ? "" : inPostProcessor;


				 //$(document).scrollTop(0); //scroll back to the top of the page
         //Second, if url is defined, build form for get request
         //execute no matter the final destination is
         if ((curURL != "")) {
            $.ajax({
               type: "get",
               url: curURL,
               data: curRequest,
               dataType: "text",
               beforeSend: function() {
                                //$.UI_ShowWaitSmall(curTarget);  // Display loading graphic
                                if(curPreProcessor != "")       // Execute Pre-processor
                                    eval(curPreProcessor);
                            },
               success: function(curResponse) {
               						 if ( typeof $.CMS_ReadResponse != 'function' )
               						 	 return false;
                           tempContent = $.CMS_ReadResponse(curResponse);               // Check response for an error message
                           tempContent = $.CMS_Cleanser(tempContent, curCleanser);      // Cleanup text...remove styles and such         
                           if (curTarget != "") { //Qin, only when the destination is defined
	                           $(curTarget).html(tempContent);                              // Move clean content to destination
	               						 //$.CMS_RewriteLinks('#contentMain');
	                           $.CMS_Integrator(curTarget);                                 // Replace link/form destinations
	                   }
                           if(curPostProcessor != "")                                   // Execute Post processor
                               	eval(curPostProcessor);
                               //$.CMS_HistoryApply();
                           //alert($(curTarget).html());                                // Visually verify html code
                         },
                failure: function () {
                           this.CMS_ShowError(curTarget);
                         }
            });
        }
        else {
            $.UI_Alert('Sorry, there is a problem with this page. Our team is looking into the issue');
        } 
        return false;
    },
    
    CMS_HistoryApply: function () {
    
    $('a.remote').jsRemote('#contentMain', function() {
            if (window.console && window.console.info) {
                console.info('content loaded');
            }
        });
    },
    
    CMS_Login: function(inForm, inTarget, errTarget, inMethod, inPreProcessor, inPostProcessor, inCleanser, inRequest) {
        /**
         * Get page content
         */
         // Set variable defaults
         var curForm = (inForm == null || inForm == "") ? "$('#standardForm')" : $("#"+inForm);
         var curFormObj = (inForm == null || inForm == "") ? eval("document.standardForm") : eval("document."+inForm);
         var curTarget = (inTarget == null || inTarget == "") ? "#bodyContainer" : inTarget;
         var curRequest = (inRequest == null || inRequest == "") ? "" : inRequest; 
         var curMethod = (inMethod == null || inMethod == "") ? "post" : inMethod;
         var curCleanser = (inCleanser == null || inCleanser == "") ? "" : inCleanser;
         var curPreProcessor = (inPreProcessor == null || inPreProcessor == "") ? "" : inPreProcessor;
         var curPostProcessor = (inPostProcessor == null || inPostProcessor == "") ? "" : inPostProcessor;

         // Handle Form by replicating data from the existing form to the AJAX form
         if (curForm != null) {
             var curURL = curForm.attr("action");

             for ( var x = 0; x < curFormObj.elements.length; x++) {
                curRequest = curRequest + "&" + curFormObj.elements[x].name + "=" + curFormObj.elements[x].value;
             }
         }
         //Second, if url is defined, build form for get request
         if ((curURL != "")&&(curTarget != "")) {
            $.ajax({
               type: curMethod,
               url: curURL,
               data: curRequest,
               dataType: "json",
               beforeSend: function() {
                                if(curPreProcessor != "")                               // Execute Pre-processor
                                    eval(curPreProcessor);
                            },
               success: function(curResponse, curStatus) {
	               //alert("error:"+curResponse.error);
					if(typeof(curResponse.error) != 'undefined')
					{
						if(curResponse.error != '')
						{
	                           $(errTarget).html(curResponse.error);                              // show the error message at the error div
						}else
						{
							//succeed, display succeed content
                           //tempContent = $.CMS_ReadResponse(curResponse);               // Check response for an error message
                           //tempContent = $.CMS_Cleanser(tempContent, curCleanser);      // Cleanup text...remove styles and such         
                           //$(curTarget).html(tempContent);                              // Move clean content to destination
                           //$.CMS_Integrator(curTarget);                                 // Replace link/form destinations
                           $.LoadPage("main.php", curTarget);
                           if(curPostProcessor != "")                                   // Execute Post processor
                               eval(curPostProcessor);
						}
					}
                           //alert($(curTarget).html());                                // Visually verify html code
                         },
                failure: function () {
                           $.CMS_ShowError(curTarget);
                         }
            });
        }
        else {
            $.UI_Alert('Sorry, there is a problem with this page. Our team is looking into the issue');
        } 
        return false;
    },
    
    //---    
    CMS_SendForm: function(inForm, inTarget, inMethod, inPreProcessor, inPostProcessor, inCleanser, inRequest) {
        /**
         * Get page content
         */
         // Set variable defaults
         var curForm = (inForm == null || inForm == "") ? "$('#standardForm')" : $("#"+inForm);
         var curFormObj = (inForm == null || inForm == "") ? eval("document.standardForm") : eval("document."+inForm);
         var curTarget = (inTarget == null || inTarget == "") ? "#bodyContainer" : inTarget;
         var curRequest = (inRequest == null || inRequest == "") ? "" : inRequest; 
         var curMethod = (inMethod == null || inMethod == "") ? "post" : inMethod;
         var curCleanser = (inCleanser == null || inCleanser == "") ? "" : inCleanser;
         var curPreProcessor = (inPreProcessor == null || inPreProcessor == "") ? "" : inPreProcessor;
         var curPostProcessor = (inPostProcessor == null || inPostProcessor == "") ? "" : inPostProcessor;

         // Handle Form by replicating data from the existing form to the AJAX form
         if (curForm != null) {
             //var curURL = curForm.attr("action");
             var curURL = curFormObj.action;
             var e_value = "";
             var varName = "";

             for ( var x = 0; x < curFormObj.elements.length; x++) {
                //find out value
                //alert("x:"+curFormObj.elements[x].name+" value:"+curFormObj.elements[x].value+" type:"+curFormObj.elements[x].type);
                varName = "";
                if (curFormObj.elements[x].type == "select-multiple") {
	                //alert(($("#"+x).val());
	                var multi_select = curFormObj.elements[x];
	                e_value = "";
					for( var i=0; i < multi_select.length; i++ ){
						// if the element is selected, get the selected values
						if( multi_select[i].selected ){
							// append the selected value, if the value property doesn't exist, use the text
							//v.push(getOptionVal(this[i]));
							e_value = e_value + multi_select[i].value + ",";
						}
					}
					if (e_value.length > 1) {
						//take out the last comma
						e_value = e_value.substr(0,e_value.length-1);
					}
					//alert(e_value);
					varName = curFormObj.elements[x].name + "=" + e_value;
            	} else {
	            	if (curFormObj.elements[x].type == "radio") {
		            	//alert(curFormObj.elements[x].checked);
							if( curFormObj.elements[x].checked ){
								e_value = curFormObj.elements[x].value;
			            		varName = curFormObj.elements[x].name + "=" + e_value;
							} else {
			            		varName = "";
							}
	            	} else {
	            		e_value =  curFormObj.elements[x].value;
	            		
	            		varName = curFormObj.elements[x].name + "=" + e_value;
            		}
            	}
            	if (varName != "") {
                	curRequest = curRequest + "&" + varName; //curFormObj.elements[x].name + "=" + e_value;
            	}
             }
         }
         //Second, if url is defined, build form for get request
         if ((curURL != "")&&(curTarget != "")) {
            $.ajax({
               type: curMethod,
               url: curURL,
               data: curRequest,
               dataType: "text",
               beforeSend: function() {
                                if(curPreProcessor != "")                               // Execute Pre-processor
                                    eval(curPreProcessor);
                            },
               success: function(curResponse, curStatus) {
                           tempContent = $.CMS_ReadResponse(curResponse);               // Check response for an error message
                           tempContent = $.CMS_Cleanser(tempContent, curCleanser);      // Cleanup text...remove styles and such         
                           $(curTarget).html(tempContent);                              // Move clean content to destination
                           //$.CMS_Integrator(curTarget);                                 // Replace link/form destinations
                           if(curPostProcessor != "")                                   // Execute Post processor
                               eval(curPostProcessor);
                           //alert($(curTarget).html());                                // Visually verify html code
                         },
                failure: function () {
                           $.CMS_ShowError(curTarget);
                         }
            });
        }
        else {
            $.UI_Alert('Sorry, there is a problem with this page. Our team is looking into the issue');
        } 
        return false;
    },
    
    CMS_UploadFile: function(inURL, inTarget, fileId, inPreProcessor, inPostProcessor, inCleanser, inRequest) {
        /**
         * Get page content
         */
         // Set variable defaults
         var curURL = (inURL == null) ? "" : inURL;
         var curTarget = (inTarget == null || inTarget == "") ? "#bodyContainer" : inTarget;
         var curRequest = (inRequest == null || inRequest == "") ? "" : inRequest; 
         var curCleanser = (inCleanser == null || inCleanser == "") ? "" : inCleanser;
         var curPreProcessor = (inPreProcessor == null || inPreProcessor == "") ? "" : inPreProcessor;
         var curPostProcessor = (inPostProcessor == null || inPostProcessor == "") ? "" : inPostProcessor;

         if (curURL != "") {
				$("#loading")
				.ajaxStart(function(){
					$(this).show();
				})
				.ajaxComplete(function(){
					$(this).hide();
				});
	
				$.ajaxFileUpload
				(
					{
						url:curURL,
						secureuri:false,
						fileElementId:fileId,
						dataType: 'json',
			            beforeSend: function() {
	                            if(curPreProcessor != "")                               // Execute Pre-processor
	                                eval(curPreProcessor);
			            	},
						success: function (data, status)
						{
							if(typeof(data.error) != 'undefined')
							{
								if(data.error != '')
								{
									alert(data.error);
	
								}else
								{
									alert(data.msg);
		                           tempContent = $.CMS_ReadResponse(data);               // Check response for an error message
		                           tempContent = $.CMS_Cleanser(tempContent, curCleanser);      // Cleanup text...remove styles and such         
		                           $(curTarget).html(tempContent);                              // Move clean content to destination
		                           //$.CMS_Integrator(curTarget);                                 // Replace link/form destinations
		                           if(curPostProcessor != "")                                   // Execute Post processor
		                               eval(curPostProcessor);
		                           //alert($(curTarget).html());                                // Visually verify html code
								}
							}
						},
						error: function (data, status, e)
						{
							alert(e);
	                        $.CMS_ShowError(curTarget);
						}
					}
				)
			}
        else {
            $.UI_Alert('Sorry, there is a problem with this page. Our team is looking into the issue');
        } 
        return false;
    },
    
    CMS_ReadResponse:function (curResponse) {
        var outResponse = "";
        if(curResponse.toLowerCase().indexOf('fatal error')>0||curResponse==''){
            // Naughty Response...send it to bed...no desert!
            //alert('error on '+curResponse.toLowerCase());
            //alert('error on '+curResponse.toLowerCase().indexOf('fatal error'));
            $.CMS_ShowError();
        }
        else{
            // Nice Response - ship the beast.
            outResponse = curResponse;
        }
        return outResponse;
    },
       
    CMS_ShowError: function(inTarget) {
        var curTarget = (inTarget == null || inTarget == "") ? "" : inTarget;
        $(curTarget).text("<center>The page couldn't be found.</center>");
    },
    
     
    
    CMS_Cleanser: function(inText, inRun) {
        /**
         * RegEx: run regex against content
         */
         
        var curText = (inText == null) ? "" : inText;
        var curRun = (inRun == null) ? "" : inRun;

        //Get HTML element if it exists
        if (curText != "") {

           switch(curRun) {
              case "all":
                  curText = this.CMS_Cleanse_Styles(curText);
                  curText = this.CMS_Cleanse_Scripts(curText);
              break; 
              
              case "styles":
                  curText = this.CMS_Cleanse_Styles(curText);
              break; 
              
              case "scripts":
                  curText = this.CMS_Cleanse_Scripts(curText);
              break;   
               
              default:
                 // Do nothing
           }
        }
        
        return curText;
    },
    
    CMS_Cleanse_Scripts: function (inText){
        /*
         * Replace Script tags
         */
        var curText = (inText == null) ? "" : inText;

        if (curText != "") {
            tempExp = new RegExp("<script", "gim");
            curText = curText.replace(tempExp, "<noscript");
            
            tempExp = new RegExp("</script>", "gim");
            curText = curText.replace(tempExp, "</noscript>");
            
            tempExp = new RegExp("onsubmit", "gim");
            curText = curText.replace(tempExp, "noonsubmit");
            
            tempExp = new RegExp("onclick", "gim");
            curText = curText.replace(tempExp, "noonclick");
            
            tempExp = new RegExp("onmouseover", "gim");
            curText = curText.replace(tempExp, "noonmouseover");
            
            /*
             * Remove embedded
             */
            tempExp = new RegExp("<embed", "gim");
            curText = curText.replace(tempExp, "<noembed");
         }
         
         return curText;
    },
    
     CMS_Cleanse_Styles: function (inText){
        /*
         * remove class and style parameters for ALL tags
         */
        var curText = (inText == null) ? "" : inText;
        
        if (curText != "") {

            // First, clean up styles and text 
             var tempExp = new RegExp("style", "gim");
             var curText = curText.replace(tempExp, "nostyle");
             
             tempExp = new RegExp("class", "gim");
             curText = curText.replace(tempExp, "noclass");
             
             tempExp = new RegExp("bgcolor", "gim");
             curText = curText.replace(tempExp, "nobgcolor");
             
             tempExp = new RegExp("font", "gim");
             curText = curText.replace(tempExp, "nofont"); 
            
            /*
             * make sure we don't allow external css includes
             */
            tempExp = new RegExp("<link", "gim");
            curText = curText.replace(tempExp, "<nolink");
            
            tempExp = new RegExp("</link>", "gim");
            curText = curText.replace(tempExp, "</nolink>"); 
            
             /* 
             * remove all html comments
             */
             tempExp = new RegExp("<!--.*-->", "gim");
             curText = curText.replace(tempExp, ""); 
         }
         
         return curText;
    },


    CMS_Integrator: function(inTarget) {
        // Integrate forms and urls into site
        var curTarget = (inTarget == null || inTarget == "") ? "" : inTarget;

        /*
         * Form Integration
         */
         $(curTarget+" form").each(
            function()
            {
                $(this).attr("action", $(this).attr('action'));
                $(this).submit(
                        function() { $.CMS_SendForm(this); return false; }
                    );
             }
         );
         
    },
    
    CMS_RewriteLinks: function(inTargetName) {
    	$(inTargetName + ' a').each( function() {
    		//make sure the hashes are applied
    		if ( typeof $(this).attr == 'function' && typeof $(this).attr('href') != 'undefined' )
    		{
    			var curHref = $(this).attr('href');
    			if ( curHref == '#' || curHref == '' )
    			{
    				if ( $(this).attr('title') != '' )
    				{
    					curHref = '#' + $(this).attr('title');
    				}
    				else if ( $(this).attr('name') != '' )
  					{
  						curHref = '#' + $(this).attr('name');
  					}
  					else
						{
							curHref = '#' + $(this).text().replace(new RegExp('view our selection of ', 'gi'), '');
						}
    			}
    			else if ( curHref[0] == '/' )
  				{
  					curHref = '#' + curHref.substring(1, curHref.length);
  				}
  				curHref = curHref.replace(new RegExp(' ', 'g'), '_');
  				$(this).attr('href', curHref);
  				if ( $(this).attr('title') == '' )
  				{
  					$(this).attr('title', curHref.replace('#', ''));
  				}
  				//hash rewriter for product detail links
  				if ( typeof $(this)[0].onclick == 'function' )
  				{
  					//console.log("looking for pd for '" + $(this)[0].toString() + "'"); //debug
	  				var onclickstr = $(this)[0].onclick.toString();
  					//console.log("		onclick: '" + onclickstr + "'"); //debug
	  				if( onclickstr.indexOf("Content_ProductDetails") > 0 )
	  				{
	  					//console.log("		pd found");
	  					var search_for = "$.Content_ProductDetails("; 
	  					var s_pos = onclickstr.indexOf(search_for) + search_for.length; 
	  					var e_pos = onclickstr.indexOf(");"); 
	  					$(this).attr('href', '/#/wine/product/' + onclickstr.substring(s_pos, e_pos));
	  					$(this).attr('title', '/wine/product/' + onclickstr.substring(s_pos, e_pos));
	  				}
	  			}
    		}
    	});
    	//set up the remote history for the new links
    	//$(inTargetName + ' a').remote('#mt', remoteHistoryCallBack);
    }
});