// Script	Widget management, position retention, page setup
// Copyright    ©2010 Cheshire West & Chester Council
// Author       Chris Weedall

// WidgetZone instance
function WidgetZone(id, connectsWith) {
    this.ID = id;
    this.ConnectsWith = connectsWith;
    this.ZoneReference = null;
}
// Widget instance
function Widget(index, id, widgetZoneID) {
    this.Index = index;
    this.ID = id;
    this.WidgetZoneID = widgetZoneID;
    this.Minimized = 0;
    this.Hidden = 0;
    this.Position = 0;
    this.GetInfoForCookie = function() {
        return this.WidgetZoneID.replace("Template_", "") + "." + this.ID + "." + this.Position + "." + this.Minimized;
    };
}
// after a widget is moved update its position details
function UpdateWidgetInfo(zone) {
    var widgets = $(zone).sortable("toArray");
    for (var w = 0; w < widgets.length; w++) {
        var index = GetWidgetIndexFromID(widgets[w]);
        widgetArray[index].WidgetZoneID = $(zone).attr("ID");
        widgetArray[index].Position = w;
    }
}
// extract the index value from a full widgetID e.g. Widget_1_2_RssViewer returns 1
function GetWidgetIndexFromID(widgetID) {
    return widgetID.substring(7, widgetID.indexOf("_", 7));
}
// extract the ID value from a full widgetID e.g. Widget_1_2_RssViewer returns 2
function GetWidgetIDFromID(widgetID) {
    return widgetID.substr(widgetID.indexOf("_", 7) + 1);
}
// define a layout column
function InitColumn(column, connectWith) {
    $(column).sortable();
    $(column).sortable('option', 'connectWith', connectWith);
    $(column).sortable('option', 'handle', '.widget_header');
    $(column).sortable('option', 'opacity', 0.6);
    if (!$.browser.msie) $(column).sortable('option', 'revert', true);
    $(column).sortable('option', 'forcePlaceHolderSize', true);
    $(column).sortable('option', 'placeholder', 'place_holder');
    $(column).sortable('option', 'tolerance', 'pointer');
    $(column).sortable('option', 'cursor', 'move');
    $(column).bind('sortreceive', function(event, ui) {
        UpdateWidgetInfo(column);
    });
    $(column).bind('sortstop', function(event, ui) {
        UpdateWidgetInfo(column);
        UpdateLayoutCookie();
    });
}
// update the layout cookie
function UpdateLayoutCookie() {
    // get layout info for cookie
    var layoutInfo = "";
    for (var w = 1; w < widgetArray.length; w++) {
        if (widgetArray[w].Hidden == 0) layoutInfo = layoutInfo + widgetArray[w].GetInfoForCookie() + "~";
    }
    // save cookie
    var cookieOptions = { path: '/', expires: 365 };
    if (layoutInfo.length > 0)
        $.cookie("CWAC.Widgets", layoutInfo, cookieOptions);
    else
        $.cookie("CWAC.Widgets", null, cookieOptions);
}
// remove widget from page and update widget info
function RemoveWidget(widget) {
    var index = GetWidgetIndexFromID($(widget).attr("id"));
    widgetArray[index].Hidden = 1;
    var title = $(widget).find(".widget_header").find("H2").text();
    $("#Template_OtherWidgets").append("<div class=\"addButton\"><a href=\"?action=add&amp;widget=" + widgetArray[index].ID + "\" title=\"Add " + title + " to your page\">" + title + "</a></div>");
    $(widget).remove();
    UpdateLayoutCookie();
}
// minimize any widgets initially decorated with m class
function InitialMinMaxWidget(widget) {
    var widgetBody = $(widget).find(".widget_content");
    $(widgetBody).removeAttr("style");
    $(widgetBody).hide();
    var index = GetWidgetIndexFromID($(widget).attr("id"));
    widgetArray[index].Minimized = 1;
    var widgetMin = $(widget).find(".minimize");
    widgetMin.css("backgroundImage", "url('/images/min_down.png')");
}
// minimize widgets on demand and update cookie
function MinMaxWidget(widget) {
    var widgetBody = $(widget).find(".widget_content");
    var widgetMin = $(widget).find(".minimize");
    $(widgetBody).slideToggle();
    if ($(widget).hasClass("m")) {
        $(widget).removeClass("m");
        var src = "\"/images/min_up.png\"";
        widgetMin.css({ "background-image": "url(" + src + ")" });
    }
    else {
        $(widget).addClass("m");
        var src = "\"/images/min_down.png\"";
        widgetMin.css({ "background-image": "url(" + src + ")" });
    }
    var index = GetWidgetIndexFromID($(widget).attr("id"));
    widgetArray[index].Minimized = $(widget).hasClass("m") ? 1 : 0;
    UpdateLayoutCookie();
}
// show/hide settings
function ShowHideSettings(widget) {
    var widgetSettings = $(widget).find(".widget_settings");
    if (widgetSettings) {
        $(widgetSettings).slideToggle();
    }
}
// show/hide add to this page
function ShowHideAddToThisPage() {
    $('#Template_OtherWidgets').slideToggle('fast');
}
// show/hide add to this page
function ShowHideHelp() {
    $('#Template_Help').toggle();
}
// define widget zones
var widgetZoneArray = new Array();
widgetZoneArray[0] = new WidgetZone("#Template_zone1", "#Template_zone2,#Template_zone3");
widgetZoneArray[1] = new WidgetZone("#Template_zone2", "#Template_zone1,#Template_zone3");
widgetZoneArray[2] = new WidgetZone("#Template_zone3", "#Template_zone1,#Template_zone2");
// create array for current widgets
var widgetArray = new Array();
var widgetCount = 1;
// fires when page has finished loading/rendering
$(function() {
    // init widget zones
    for (var z = 0; z < widgetZoneArray.length; z++) {
        widgetZoneArray[z].ZoneReference = $(widgetZoneArray[z].ID);
        InitColumn(widgetZoneArray[z].ID, widgetZoneArray[z].ConnectsWith);
    }
    // init widgets
    $(".widget").each(function() {
        var widgetID = $(this).attr("id");
        var index = GetWidgetIndexFromID(widgetID);
        var id = GetWidgetIDFromID(widgetID);
        widgetArray[widgetCount] = new Widget(index, id, $(this).parent().attr("id"));
        widgetCount++;
    });
    // remember starting positions
    for (var z = 0; z < widgetZoneArray.length; z++) { UpdateWidgetInfo(widgetZoneArray[z].ZoneReference); }
    // set initial widget min/max state
    $(".widget.m").each(function() { InitialMinMaxWidget($(this)); });
    // add widgets
    $("#add_section .add").find("A").attr("href", "javascript:ShowHideAddToThisPage();");
    $("#add_section .help").find("A").attr("href", "javascript:ShowHideHelp();");
    $("#close_help").attr("href", "javascript:ShowHideHelp();");
	$("#close_me").attr("href", "javascript:ShowHideAddToThisPage();");
    // removes A tags put in to cope with noscript users
    $(".widget_header, .fixed_widget_header").find("LI:not(.rss)").find("A").remove();
    // minimize/maximize
    $(".minimize").click(function() { MinMaxWidget($(this).parents(".widget")); });
    // close
    $(".close").click(function() { RemoveWidget($(this).parents(".widget")); });
    // settings
    $(".widget_settings").hide();
    $(".settings").click(function() { ShowHideSettings($(this).parents(".widget")); });
    // add styles applicable for script users
    $(".widget_header").css("cursor", "move");
});

