// Display the Add New RSS form
function displayAddRssForm() {
    $(".configAddRssError").css("color", "#FF3030");
    $(".configAddRss").modal();
}

// Hide the Add New RSS form
function hideAddRssForm() {
    $(".configAddRssError").css("color", "#FF3030");
    $.modal.close();
}

// Process the Add Rss Form
function processAddRssForm() {
    // Validate the input 
    $(".configAddRssError").css("color", "#FF3030");
    $(".configAddRssError").html("");
    var rssUrl = $("#configAddRssUrl").attr("value");
    rssUrl = $.trim(rssUrl);
    if(rssUrl == null || rssUrl == ''){
        $(".configAddRssError").html("Invalid Rss feed provided. Please try again.");
        return;
    }

    // Perform Ajax request to verify rssUrl
    ajaxCall("verifyrssurrl",
             "newRssUrl=" + escape(rssUrl),
             function(theResult){
                if(theResult.result != 'success'){
                    $(".configAddRssError").html("Invalid Rss feed provided. Please try again.");
                    return;
                } else {
                    // Get the current config
                    var stJSONConfig = $(".SlotJSON").attr("value");
                    var jsonArray = eval('(' + stJSONConfig + ')');
                    
                    var currentSlotCount = jsonArray.length;
                    if(!canAddMoreSlots(currentSlotCount)){
                        // Shouldnt be here
                        $(".configAddRssError").html("Sorry maximum Slot Count has been allocated.");
                        return;
                    }
                    
                    var blockstyleobj = (blockstyleobj||{ backgroundImage: "url(App_Themes/Travolution/Images/loader.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: '100px 60px', backgroundColor: '#e3e3e3', opacity: '0.7', width : '374px', height : '170px', fontfamily : 'Verdana', fontweight : 'bold'  });
                    $(".modalContainer").block({
                                    message: "<p style='font-weight:bold;margin-top:70px;'>Please wait...</p>",
                                    css: blockstyleobj                        
                                    });
                                    
                    // Perform Ajax request
                    ajaxCall("personaliseadd",
                             "newRssUrl=" + escape(rssUrl),
                             function(theResult){
                                if(theResult.result == 'success'){
                                    // Display the new slot
                                    var theResultObject = eval(theResult.data);
                                    var theHtml = HtmlDecode(theResultObject.slotHTML);
                                    $(".col-1").prepend(theHtml);
                                    $(".RssEditControl[slotID='" + theResultObject.slotID  + "']").fadeIn();
                                    initSortable();
                                    
                                    // Update slot configuration
                                    $(".SlotJSON").attr("value", theResultObject.newSlotJson);
                                    
                                    // Display the confirmation
                                    $(".configAddRssError").html("RSS feed added to page!");
                                    $(".configAddRssError").css("color", "#006400");
                                    $("#configAddRssUrl").attr("value", "");
                                }
                             }
                             ,".modalContainer",null,null);
                }
         },null,"",null);
}

// Helper functions for maintaining amendments to slots
function canAddMoreSlots(currentSlotCount){
    if(currentSlotCount >= 12){
        return false;
    }else{
        return true;
    }
}

// Display/Hide Slot config
function displayHideSlotConfig(slotID) {
    // Get the edit pane handle
    var editPane = $(".RssEditControl[slotID='" + slotID  + "'] .RssEditControlContainer .RssEditControlConfig");
    var displaySettings = editPane.css("display");
    if(displaySettings == 'none'){
        // Put config settings in form
        var stSlotConfig = $(".RssEditControl[slotID='" + slotID  + "']").attr("slotConfig");
        var slotConfigAr =  eval('(' + stSlotConfig + ')');
        editPane.find("input[name='title']").attr("value", slotConfigAr.Title);
        editPane.find("input[name='url']").attr("value", slotConfigAr.RssUrl);
        editPane.find("select[name='noOfItems']").attr("value", slotConfigAr.ItemCount);
        editPane.find("select[name='viewType']").attr("value", slotConfigAr.ViewType);
        if(slotConfigAr.OpenInNewWindow){
            editPane.find("input[name='openInNewWindow']").attr("checked", 'checked');
        }else{
            editPane.find("input[name='openInNewWindow']").attr("checked", '');
        }
        editPane.slideToggle("fast");
    }else{
        editPane.slideToggle("fast");
    } 
}

function performSlotUpdate(slotID) {
    // Validate the new values
    
    var editPane = $(".RssEditControl[slotID='" + slotID  + "'] .RssEditControlContainer .RssEditControlConfig");
    var newTitle =  editPane.find("input[name='title']").attr("value").replace(/<\/?[^>]+(>|$)/g, "");
    var newRssUrl = editPane.find("input[name='url']").attr("value");
    var newNoItems = editPane.find("select[name='noOfItems']").attr("value");
    var newViewType = editPane.find("select[name='viewType']").attr("value");
    var newOpenInNewWindow = editPane.find("input[name='openInNewWindow']").attr("checked");
    
    // Existing values
    var stExSlotConfig = $(".RssEditControl[slotID='" + slotID  + "']").attr("slotConfig");
    var existingSlotConfigAr =  eval('(' + stExSlotConfig + ')');
        
    // Perform Ajax request to verify rssUrl
    ajaxCall("verifyrssurrl",
             "newRssUrl=" + escape(newRssUrl),
             function(theResult){
                if(theResult.result != 'success'){
                    var rssControldetails = $(".RssEditControl[slotID='" + slotID  + "']").children(".RssEditControlContainer").children(".RssEditControlDetails");
                    rssControldetails.html("Invalid feed entered. Please try again.");
                    rssControldetails.css("color", "#FF3030");
                    rssControldetails.css("font-weight", "bold");
                    return;
                } else {
                    var newJson = {};
                    newJson.SlotID = slotID;
                    newJson.RssUrl = newRssUrl;
                    newJson.Title = newTitle;
                    newJson.ItemCount = newNoItems;
                    newJson.ViewType = newViewType;
                    newJson.Minimised = existingSlotConfigAr.Minimised;
                    if(newOpenInNewWindow == 'checked'){
                        newJson.OpenInNewWindow = true;
                    }else{
                        newJson.OpenInNewWindow = false;
                }
                    
                // Perform Ajax request
                var stNewJson = escape(JSON.stringify(newJson));
                ajaxCall("personaliseupdate",
                         "slotupdatedetails=" + stNewJson,
                         function(theResult){
                            if(theResult.result == 'success'){
                                // Display the updated slot details
                                var theResultObject = eval(theResult.data);
                                var theHtml = HtmlDecode(theResultObject.slotHTML);
                                var theOldOne = $(".RssEditControl[slotID='" + slotID  + "']");
                                theOldOne.before(theHtml);
                                theOldOne.remove();
                                
                                // Update slot configuration
                                $(".SlotJSON").attr("value", theResultObject.newSlotJson);
                                initSortable();
                            }
                         }
                         ,null,"",null);
                }
             }
             ,null,"",null);    
}

// Minimise/Maximise the slots contents
function minMaxSlotControl(slotID, imgID) {
    // Get the contents pane handle
    var contentsPane = $(".RssEditControl[slotID='" + slotID  + "'] .RssEditControlContainer .RssEditControlDetails");
    var displaySettings = contentsPane.css("display");
    if(displaySettings == 'none'){
        $("#" + imgID).attr("src", "App_Themes/Travolution/Images/ctrl-min.gif");
        contentsPane.slideToggle("fast");
    }else{
        $("#" + imgID).attr("src", "App_Themes/Travolution/Images/ctrl-max.gif");
        contentsPane.slideToggle("fast");
    }    
    performSlotMinimiseUpdate(slotID);
}
function performSlotMinimiseUpdate(slotID) {
        
    // Existing values
    var stExSlotConfig = $(".RssEditControl[slotID='" + slotID  + "']").attr("slotConfig");
    var existingSlotConfigAr =  eval('(' + stExSlotConfig + ')');
    if(existingSlotConfigAr.Minimised){
        existingSlotConfigAr.Minimised = false;
    }else{
        existingSlotConfigAr.Minimised = true;
    }
        
    // Perform Ajax request
    var stNewJson = escape(JSON.stringify(existingSlotConfigAr));
    ajaxCall("personaliseupdate",
             "slotupdatedetails=" + stNewJson,
             function(theResult){
                if(theResult.result == 'success'){
                    // Display the updated slot details
                    var theResultObject = eval(theResult.data);           
                    // Update slot configuration
                    $(".SlotJSON").attr("value", theResultObject.newSlotJson);
                }
             }
             ,null,"",null);
}

// Remove slot
function removeSlot(slotID) {
    // Perform Ajax request
    ajaxCall("personaliseremove",
             "slotid=" + slotID,
             function(theResult){
                if(theResult.result == 'success'){
                    // Remove the slot
                    var theResultObject = eval(theResult.data);
                    var slotPane = $(".RssEditControl[slotID='" + slotID  + "']");
                    slotPane.fadeOut("normal", function(){
                                                    slotPane.remove(); 
                                                    initSortable();
                                                });                 
                    // Update slot configuration
                    $(".SlotJSON").attr("value", theResultObject.newSlotJson);
                }
             }
             ,null,"",null);
}

// Reset slots
function resetSlots() {
    // Perform Ajax request
    ajaxCall("personalisereset",
             "",
             function(theResult){
                if(theResult.result == 'success'){
                    // Remove the slots
                    var theResultObject = eval(theResult.data);
                    if($(".RssEditControl").length > 0){
                        $(".RssEditControl").fadeOut("normal", function(){
                                                    $(".RssEditControl").remove();  
                                                    // Add the new slots
                                                    var theHtml = HtmlDecode(theResultObject.slotHTML);
                                                    $(".col-1").html(theHtml);
                                                    $(".RssEditControl").fadeIn();
                                                    initSortable();
                                    }); 
                    }else{   
                          var theHtml = HtmlDecode(theResultObject.slotHTML);
                          $(".col-1").html(theHtml);
                          $(".RssEditControl").fadeIn();
                          initSortable();
                    }               
                    // Update slot configuration
                    $(".SlotJSON").attr("value", theResultObject.newSlotJson);
                }
             }
             ,null,"",null);
}

// Generix Ajax handler
function ajaxCall(operation,data,callback,blocker,blockmsg,blockstyleobj){
    if (blocker){
        // Make sure block hasn't already been applied
        if($(".blockUI").length == 0){
            blockmsg = (blockmsg||'Please wait..');
            blockstyleobj = (blockstyleobj||{ backgroundImage: "url(App_Themes/Travolution/Images/loading.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundColor: '#e3e3e3', opacity: '0.7' });
            $(blocker).block({
                            message: blockmsg,
                            css: blockstyleobj                        
                            });
        }
    } 
    
    var req = $.ajax({
                type: "POST",
                url: "RequestHandler.ashx?op="+operation,
                data: data,
                error: function(req, json, er){
                            if (blocker){ $(blocker).unblock(); }
                            return;
                       },
                success: function(json){
                            var response = eval('(' + json + ')');
                            if (blocker){ $(blocker).unblock(); }
                            if (response.result=="success" || response.result=="failure"){
                                callback(response);
                            }else if(response.result=="error"){
                                if(response.data != ""){
                                }
                            }
                            return;
                        }
              });
            
    setTimeout(function(){
                    if(req && req.readyState!=4){
                        req.abort();
                        if(blocker){
                            $(blocker).unblock();
                        }
                    }
               }, 60000);    
}

function initSortable(){
    $('.col-1').sortable("refresh");
}

function sortChanged(e, ui){
    var blockHeight = $(".col-1").height() + 'px';
    var blockWidth = $(".col-1").width() + 'px';
    var blockstyleobj = (blockstyleobj||{ backgroundImage: "url(/App_Themes/Travolution/Images/bgloader.gif)", backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', backgroundColor: '#e3e3e3', opacity: '0.7', height : '100%', width : '100%' });
    $(".col-1").block({
                    message: "<div style='width:" + blockWidth + ";height:" + blockHeight + ";'></div>",
                    css: blockstyleobj                        
                    });

    setTimeout(function(){                        
                // Get an array of the sortable controls
                var stSlotConfig = "[";
                var sortableControls = $(".RssEditControl");
                var sortableControlsIDs = $(".RssEditControl").attr("slotid");
                var counter = 0;
                sortableControls.each(function(){   
                                        counter = counter + 1;
                                        if(counter == sortableControls.length){
                                            stSlotConfig = stSlotConfig + $(this).attr("slotConfig");
                                        }else{
                                            stSlotConfig = stSlotConfig + $(this).attr("slotConfig") + ",";
                                        }
                                      });
                var stSlotConfig = stSlotConfig + "]";
                $(".SlotJSON").attr("value", stSlotConfig);
               
                // Pereform ajax call
                ajaxCall("personalisesort",
                         "newslotconfig=" + escape(stSlotConfig),
                         function(theResult){
                            if(theResult.result == 'success'){
                                
                            }
                         }
                         ,".col-1",null,null);
             }, 1000);
}

// Helper function to decode ajax content
function HtmlDecode(EncodedString){
    var regExp = /\+/g;
    return unescape(String(EncodedString).replace(regExp, " "));
}

$(window).load(
	function () {
	    // Make controls sotrable
		$('.col-1').sortable(
			{
				items : 		'.RssEditControl',
				axis : 	        'y',
				handle:         '.RssEditControlHeader',
				placeholder:    'sorthelper',
				revert:         true,
				distance:       3,
				update:         sortChanged
			}
		);
   });