/* BUG SOLVE
 *
 * This code solves many problems related to when IE6 users have page loads set to always
 ************************************************************************************************/
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}


/* Image preload function */
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$.preloadImages("assets/ui/blue.bottom.background.gif",
                "assets/ui/blue.holder.left.background.gif",
                "assets/ui/blue.holder.right.background.gif",
                "assets/ui/blue.hook.background.gif",
                "assets/ui/blue.hook.close.gif",
                "assets/ui/blue.hook.minimise.gif",
                "assets/ui/blue.hook.options.gif",
                "assets/ui/green.bottom.background.gif",
                "assets/ui/green.holder.left.background.gif",
                "assets/ui/green.holder.right.background.gif",
                "assets/ui/green.hook.background.gif",
                "assets/ui/green.hook.close.gif",
                "assets/ui/green.hook.minimise.gif",
                "assets/ui/green.hook.options.gif",
                "assets/ui/lgreen.bottom.background.gif",
                "assets/ui/lgreen.holder.left.background.gif",
                "assets/ui/lgreen.holder.right.background.gif",
                "assets/ui/lgreen.hook.background.gif",
                "assets/ui/lgreen.hook.close.gif",
                "assets/ui/lgreen.hook.minimise.gif",
                "assets/ui/lgreen.hook.options.gif",
                "assets/ui/grey.bottom.background.gif",
                "assets/ui/grey.holder.left.background.gif",
                "assets/ui/grey.holder.right.background.gif",
                "assets/ui/grey.hook.background.gif",
                "assets/ui/grey.hook.close.gif",
                "assets/ui/grey.hook.minimise.gif",
                "assets/ui/grey.hook.options.gif",
                "assets/ui/orange.bottom.background.gif",
                "assets/ui/orange.holder.left.background.gif",
                "assets/ui/orange.holder.right.background.gif",
                "assets/ui/orange.hook.background.gif",
                "assets/ui/orange.hook.close.gif",
                "assets/ui/orange.hook.minimise.gif",
                "assets/ui/orange.hook.options.gif",
                "assets/ui/purple.bottom.background.gif",
                "assets/ui/purple.holder.left.background.gif",
                "assets/ui/purple.holder.right.background.gif",
                "assets/ui/purple.hook.background.gif",
                "assets/ui/purple.hook.close.gif",
                "assets/ui/purple.hook.minimise.gif",
                "assets/ui/purple.hook.options.gif",
                "assets/ui/bottom.background.gif",
                "assets/ui/holder.left.background.gif",
                "assets/ui/holder.right.background.gif",
                "assets/ui/hook.background.gif",
                "assets/ui/hook.close.gif",
                "assets/ui/hook.minimise.gif",
                "assets/ui/hook.options.gif",
                "assets/ui/widget-selection-panel/green.close.selection.tab.gif",
                "assets/ui/widget-selection-panel/green.holder.background.gif",
                "assets/ui/widget-selection-panel/green.module.selection.tab.gif",
                "assets/ui/widget-selection-panel/green.selection.background.gif",
                "assets/ui/widget-selection-panel/green.theme.selection.tab.gif",
                "assets/ui/widget-selection-panel/lgreen.close.selection.tab.gif",
                "assets/ui/widget-selection-panel/lgreen.holder.background.gif",
                "assets/ui/widget-selection-panel/lgreen.module.selection.tab.gif",
                "assets/ui/widget-selection-panel/lgreen.selection.background.gif",
                "assets/ui/widget-selection-panel/lgreen.theme.selection.tab.gif",
                "assets/ui/widget-selection-panel/grey.close.selection.tab.gif",
                "assets/ui/widget-selection-panel/grey.holder.background.gif",
                "assets/ui/widget-selection-panel/grey.module.selection.tab.gif",
                "assets/ui/widget-selection-panel/grey.selection.background.gif",
                "assets/ui/widget-selection-panel/grey.theme.selection.tab.gif",
                "assets/ui/widget-selection-panel/purple.close.selection.tab.gif",
                "assets/ui/widget-selection-panel/purple.holder.background.gif",
                "assets/ui/widget-selection-panel/purple.module.selection.tab.gif",
                "assets/ui/widget-selection-panel/purple.selection.background.gif",
                "assets/ui/widget-selection-panel/purple.theme.selection.tab.gif",
                "assets/ui/widget-selection-panel/orange.close.selection.tab.gif",
                "assets/ui/widget-selection-panel/orange.holder.background.gif",
                "assets/ui/widget-selection-panel/orange.module.selection.tab.gif",
                "assets/ui/widget-selection-panel/orange.selection.background.gif",
                "assets/ui/widget-selection-panel/orange.theme.selection.tab.gif",
                "assets/ui/ajax.loader.gif"
        );

/* FUNCTION trimToMaxCharWords() by Alex Kearns
 *
 * This function takes a string of words and returns a string of words that has a max char
 * length of maxcharacters. Ie, it trims words off the end of the string so the string is
 * below or equal to maxcharacters. It adds a "..." at end if words are trimmed
 ************************************************************************************************/
var trimToMaxCharWords = function(wordstring,maxcharacters) {
    var wordarray = wordstring.split(" ");
    var numwords=wordarray.length;
    var newstring="";
    var laststring="";
    for (var counter=0; counter<numwords; counter++) {
        laststring=newstring
        if (counter!=0) {
            newstring+=(" "+wordarray[counter]);
        }
        else {
            newstring+=wordarray[counter];
        }
        if (newstring.length>maxcharacters) {
            return (laststring+"...");
        }
    }
    return newstring;
}

/* FUNCTION toPropertCase()
 *
 * Caps up the first letter of all words
 * Useful for formatting user generated content.
 ************************************************************************************************/
String.prototype.toProperCase = function(){
     return this.toLowerCase().replace(/\w+/g,function(s){
          return s.charAt(0).toUpperCase() + s.substr(1);
     })
}


/* JAVASCRIPT COOKIE FUNCTIONS
 *
 * Can't remember where I got them but they are very useful
 ************************************************************************************************/
function Set_Cookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) { return null; }
    var end = document.cookie.indexOf( ";", len );
    if (end == -1) { end = document.cookie.length; }
    return unescape(document.cookie.substring(len, end));
}


/* JQUERY CODE
 *
 * Most of the code is written using the JQUERY Library. All the JQUERY Code for the widgets
 * is contained within the $(document).ready() function
 ************************************************************************************************/

$(document).ready( function() {

    /* GLOBAL VARIABLES
     *
     * Here, we define lots of global variables
     ************************************************************************************************/



    var global_widgetstates = new Array();
        global_widgetstates["type"]=0;
        global_widgetstates["position"]=1;
        global_widgetstates["colour"]=2;
        global_widgetstates["settings"]=3;
        global_widgetstates["id"]=4;

    var global_widgettypes = new Array();
        global_widgettypes["video-gallery"]=0;
        global_widgettypes["flickr-gallery"]=1;
        global_widgettypes["gig-calendar"]=2;
        global_widgettypes["hair-competition"]=3;
        global_widgettypes["music-reviews"]=4;
        global_widgettypes["music-news"]=5;
        global_widgettypes["cool-links"]=6;
        global_widgettypes["douglas-gallery"]=7;
        global_widgettypes["shockwaves-gallery"]=8;
        global_widgettypes["welcome-widget"]=9;
        global_widgettypes["product-promotion"]=10;
		global_widgettypes["nmeipod"]=11;

    var global_widgetcolours = new Array();
        global_widgetcolours['red']=0;
        global_widgetcolours['lgreen']=1;
        global_widgetcolours['grey']=2;
        global_widgetcolours['green']=3;
        global_widgetcolours['orange']=4;
        global_widgetcolours['purple']=5;



    var drag=false;
    var elementoffset;
    var dragelement;
    var originalposition;
    var dropmessageshowing=false;
    var draggedelement;
    var lastHoverWidget=-1;
    var lastHoverColumn=-1;
    var widgetSpacerPos=new Array();
    var widgetSpacerHeight;
    var columnArray="";
    var originalWidgetInfo=new Array();
    var previousWidgetPrepend=false;
    var previousWidgetAppend=false;
    var newDragWidget=false;
    var widgetDropFunction;
    var widgetKillFunction;
    var widgetKillMouseDown;
    var lastColumnWidth;
    var centreposition;
    var currentlyKilling=false;
    var browserHeightOffset=12;
    var initialiseGallery;
    var initialiseFlickrGallery;
    var widgetInsertHTML;
    var initialiseRadioPlayer;
    var initialiseVideoGallery;
    var initialiseDouglasGallery;
    var initialiseCoolLinksWidget;
    var initialiseMusicNewsWidget;
    var initialiseMusicReviewsWidget;
    var initialisePromotionWidget;
    var initialiseNmeCompetition;
	var initialiseNmeiPod;
    var currentlyAnimatingWidget=false;
    var changeWidgetColour;
    var widgetMinimise="";
    var widgetMenu="";
    var openCloseOptions="";
    var optionsCloseButton="";
    var initialiseCompetitionWidget="";
    var userId=""; // This should be updated with the user id
    var userName=""; // This should be updated with the user id
    var currentCompetition="crazyhair";
    var loginPopup;
    var initialiseWelcomeWidget;
    var currentlySelectedPanel="";
    var currentTheme="";
    var selectedTheme="";
    var selectionPanelHeight=204; // Sets how high the selectionpanel opens to

    if (Get_Cookie("shockwaves")) {
        if (Get_Cookie("shockwaves") != "signedout") {
            userId=parseInt(Get_Cookie("shockwaves").split("#$%")[0]);
            userName=Get_Cookie("shockwaves").split("#$%")[1];
            $("div#main-login-holder p.logged-in span").text(userName);
            $("div#main-login-holder p.logged-in").css({display:"block"});
            $("div#main-login-holder a.sign-in").css({display:"none"});
        }
    }

    var globalLastMusicId=0;
    function getUniqueMusicId() {
        globalLastMusicId++;
        return ("music"+globalLastMusicId)
    }

    var globalLastCompetitionId=0;
    function getUniqueCompetitionId() {
        globalLastCompetitionId++;
        return (globalLastCompetitionId)
    }

    var globalLastFlickrId=0;
    function getUniqueFlickrId() {
        globalLastFlickrId++;
        return (globalLastFlickrId)
    }

    var fileUploadUniqueId=0;
    function getUniqueFileUploadId() {
        fileUploadUniqueId++;
        return (fileUploadUniqueId)
    }

	var isSafari3=false;
    if (navigator.userAgent.indexOf("Version/3")!=-1 && navigator.userAgent.indexOf("Safari")!=-1) {
		isSafari3=true;
    }

    var isFireFox=false;
    if (navigator.userAgent.indexOf("Firefox")!=-1) {
        isFireFox=true;
    }
    var isIE = window.ActiveXObject ? true : false; // ActiveX is only used in Internet Explorer
    var isIE6=isIE;

    var isIE7=false;
    if (window.external && (typeof window.XMLHttpRequest == "object")) {
        isIE7=true;
    }

    if (isIE) {
        browserHeightOffset=2;
    }
    var debug1;

    function pageScrollY() {
        var y;
        if (self.pageYOffset) { // all except Explorer
            y = self.pageYOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
            y = document.documentElement.scrollTop;
        }
        else if (document.body) { // all other Explorers
            y = document.body.scrollTop;
        }
    return y;
    }

    function widgetCoords(widgetId,x,y,x2,y2) {
        this.widgetId=widgetId;
        this.x=x;
        this.y=y;
        this.x2=x2;
        this.y2=y2;
    }

    function columnCoords(columnId,x,y,x2,y2,widgetArray) {
        this.columnId=columnId;
        this.x=x;
        this.y=y;
        this.x2=x2;
        this.y2=y2;
        this.widgetArray=widgetArray;
    }

    $("*").mousedown( function() {
        if (drag==true)
            return false;
        else
            return true;
    });

    /* if (isIE) {
        $("body *").mousemove( function() {
            if (drag==true)
                return false;
            else
                return true;
        });
    } */

    function checkwhere(e) {
        if (document.layers){
            xCoord = e.x;
            yCoord = e.y;
        }
        else if (document.all){
            xCoord = event.clientX;
            yCoord = event.clientY;
        }
        else if (document.getElementById){
            xCoord = e.clientX;
            yCoord = e.clientY;
        }
        if (isIE || isFireFox) {
            yCoord+=pageScrollY();
        }
        return [xCoord, yCoord];
    }

    function checkoffset(e, element) {
        if (e.offsetX && !isSafari3) {
            return [e.offsetX, e.offsetY];
        }
        else {
            var temppos=findPos(element);
            if (isFireFox) {
                return [e.clientX-temppos[0], 10];
            }
            else {
                return [e.clientX-temppos[0], e.clientY-temppos[1]];
            }
        }
    }

    function findPos(obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft
            curtop = obj.offsetTop
            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }
        }
        if (isIE) {
            // curtop+=pageScrollY();
        }
        return [curleft,curtop];
    }

    var getViewportDimensions = function() {
        var x,y;
        if (self.innerHeight) // all except Explorer
        {
            x = self.innerWidth;
            y = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
            // Explorer 6 Strict Mode
        {
            x = document.documentElement.clientWidth;
            y = document.documentElement.clientHeight;
        }
        else if (document.body) // other Explorers
        {
            x = document.body.clientWidth;
            y = document.body.clientHeight;
        }
        return [x,y];
    }




    /* FUNCTION: specialFindHeight() by Alex Kearns
     *
     * This function finds the aprox height of an absolutely positioned element, by inserting it in
     * a test div and setting its position to static and display to block;
     ************************************************************************************************/
    var specialFindHeight = function(element, widthsetting) {
        var sizetester=$("div#size-tester").css({width: widthsetting});
        var newelement=$(element).clone().css({position:"static",display:"block"}).appendTo(sizetester);
        var elementheight = $(newelement).height();
        $(sizetester).empty();
        return elementheight;
    }


    /* FUNCTION: insertWidgetAjaxLoader(element) by Alex Kearns
     *
     * This function inserts a loader gif in a widget in the correct position. The loader is
     * is inserted into the element supplied
     ************************************************************************************************/
    var insertWidgetAjaxLoader = function(tempelement) {
        var loaderleftoffset=parseInt(($(tempelement).width()-220)/2);
        $(tempelement).append('<div style="left:'+loaderleftoffset+'px" class="widget-ajax-loader"><h5>Loading</h5><img src="assets/ui/ajax.loader.gif" alt="" /></div>');
        return;
    }

    /* FUNCTION: removeWidgetAjaxLoader(element) by Alex Kearns
     *
     * This function removes the ajax loader from the specified element
     ************************************************************************************************/
    var removeWidgetAjaxLoader = function(tempelement) {
        $(tempelement).find("div.widget-ajax-loader").remove();
        return;
    }

    /* FUNCTION: insertWidgetErrorMessage(element, errormessage) by Alex Kearns
     *
     * This function inserts an error message in a widget in the correct position. The message is
     * is inserted into the element supplied
     ************************************************************************************************/
    var insertWidgetErrorMessage = function(tempelement, errormessage) {
        var messageleftoffset=parseInt(($(tempelement).width()-220)/2);
        var messagedeleted=false;
        $(tempelement).append('<div style="left:'+messageleftoffset+'px" class="widget-error-message"><h5>Error</h5><p class="widget-error-message">'+errormessage+'</p><a class="close-message">X</a></div>');

        $(tempelement).find("div.widget-error-message a.close-message").click(function() {
            if (messagedeleted) {
                return false;
            }
            messagedeleted=true;
            $(tempelement).find("div.widget-error-message").remove();
            $(tempelement).find("div.stage-inner-inner").css({opacity: 1});
            return false;
        });

        setTimeout( function() {
            if (messagedeleted) {
                return false;
            }
            messagedeleted=true;
            $(tempelement).find("div.widget-error-message").animate({opacity: 0 },1000, function() {
                $(this).remove();
                $(tempelement).find("div.stage-inner-inner").css({opacity: 1});
            });
        }, 5000);

        return;
    }

    /* FUNCTION: insertLoginErrorMessage(element, errormessage) by Alex Kearns
     *
     * This function inserts a login error message in a widget in the correct position. The message is
     * is inserted into the element supplied. It also provides links to either login or sign up
     ************************************************************************************************/
    var insertLoginErrorMessage = function(tempelement, errormessage) {
        var messageleftoffset=parseInt(($(tempelement).width()-220)/2);
        var messagedeleted=false;
        // Sorry about the inline styles but there were conflicts in style
        // sheet and could not overide other styles using style sheets
        $(tempelement).append('<div style="left:'+messageleftoffset+'px" class="widget-error-message"><h5>Please login</h5><p class="widget-error-message">'+errormessage+'</p><a style="margin: 0; padding: 0; font-size: 10px" class="close-message">X</a><div class="login-error-options"><a class="login-error-signup" href="#">Sign up</a><a class="login-error-login" href="#">Log in</a></div></div>');

        $(tempelement).find("div.widget-error-message a.close-message").click(function() {
            if (messagedeleted) {
                return false;
            }
            messagedeleted=true;
            $(tempelement).find("div.widget-error-message").remove();
            $(tempelement).find("div.stage-inner-inner").css({opacity: 1});
            return false;
        });

        $(tempelement).find("div.widget-error-message a.login-error-signup").click( function() {
            $(tempelement).find("div.widget-error-message a.close-message").click();
            loginPopup("signup-panel");
            return false;
        });

        $(tempelement).find("div.widget-error-message a.login-error-login").click( function() {
            $(tempelement).find("div.widget-error-message a.close-message").click();
            loginPopup("login-panel");
            return false;
        });

        return;
    }

    /* FUNCTION: precalculateWidgetCoords() by Alex Kearns
     *
     * This function precalculates the position of the widgets. It is called when a widget is dropped
     * or when a widget is dragged after the window size has been changed
     * The widget positions are stored in a global array - columnArray
     ************************************************************************************************/
    function precalculateWidgetCoords() {
        columnArray=new Array();
        var numofcolumns=$("div#drag-column-holder").find("div.column").length;
        for (var columncounter=0; columncounter<numofcolumns; columncounter++) {
            var currentcolumn=$("div#drag-column-holder").find("div.column:eq("+columncounter+")").get()[0];
            var columnpos=findPos(currentcolumn);
            var widgetArray=new Array();
            var numofwidgets=$(currentcolumn).find("div.widget").length;
            if (numofwidgets>0) {
                for (var counter=0; counter<numofwidgets; counter++) {
                    var currentwidget=$(currentcolumn).find("div.widget:eq("+counter+")").get()[0];
                    var widgetpos=findPos(currentwidget);
                    widgetArray[widgetArray.length]= new widgetCoords(currentwidget, widgetpos[0], widgetpos[1], widgetpos[0]+$(currentwidget).width(), widgetpos[1]+$(currentwidget).height());
                }
                columnArray[columnArray.length]= new columnCoords(currentcolumn, columnpos[0], columnpos[1], columnpos[0]+$(currentcolumn).width(), columnpos[1]+$("div#drag-column-holder").height()+200, widgetArray);
            }
            else {
                columnArray[columnArray.length]= new columnCoords(currentcolumn, columnpos[0], columnpos[1], columnpos[0]+$(currentcolumn).width(), columnpos[1]+$("div#drag-column-holder").height()+200, []);
            }
        }
    lastColumnWidth=$("div#drag-column-holder div.column:eq(0)").width();
    }

    /* FUNCTION: findWidgetPos() by Alex Kearns
     *
     * This function finds the column and position within that column for any visible widget
     * It takes the widget dom id and returns the column number and row number in an array
     ************************************************************************************************/
    function findWidgetPos(element) {
        var numofcolumns=$("div#drag-column-holder").find("div.column").length;
        for (var columncounter=0; columncounter<numofcolumns; columncounter++) {
            var currentcolumn=$("div#drag-column-holder").find("div.column:eq("+columncounter+")").get()[0];
            var numofwidgets=$(currentcolumn).find("div.widget").length;
            for (var counter=0; counter<numofwidgets; counter++) {
                if (columnArray[columncounter].widgetArray[counter].widgetId == element) {
                    return [columncounter, counter];
                }
            }
        }
    return false;
    }


    /* FUNCTIONS takeYear and leadingZero courtesy quirks mode
     *
     * A couple of javascript help functions. The first details with a JS bug in Netscape
     * The second simply adds a zero at the start of any one digit number
     ************************************************************************************/
    function takeYear(theDate) {
        x = theDate.getYear();
        var y = x % 100;
        y += (y < 38) ? 2000 : 1900;
        return y;
    }

    function leadingZero(nr) {
        if (nr < 10) nr = "0" + nr;
        return nr;
    }

    /* FUNCTION generateCalendar by Alex Kearns
     *
     * This function generates the html for a calendar for any month,
     * and inserts the html into the specified element. The function also adds events
     * for when particular days are clicked or new months selected
     * Note that this function works with the JQuery library
     ************************************************************************************/
    generateCalendar = function(calendarMonth,calendarYear,insertelement, selectedDate) {
        var daysArray = new Array('Sunday','Monday','Tuesday','Wednesday', 'Thursday','Friday','Saturday');
        var monthsArray = new Array("January","February","March","April","May","June", "July","August","September","October","November","December");
        var global_oneDay=1000*60*60*24;
        var suffixArray=new Array("st","nd","rd","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th", "st","nd","rd","th","th","th","th","th","th","th","st","nd","rd","th","th","th","th","th","th","th");

        var selectedDay=selectedDate.getDate();
        var selectedWeekDay=selectedDate.getDay();
        var selectedMonth=selectedDate.getMonth()
        var selectedYear=takeYear(selectedDate);

        // FOM stands for First of the Month
        var FOM = new Date(calendarYear,calendarMonth,1);
        FOMWeekDay=FOM.getDay();

        // What day of week. Then work out how many blank entries at start of calendar
        // This later value is stored in FOMDayOffset
        var FOMDayOffset=FOMWeekDay-1;
        if (FOMDayOffset==-1) {
            FOMDayOffset=6;
        }

        var nextMonth = new Date(calendarYear,(calendarMonth+1),1);

        // Work out length of month
        var FOMMonthLength=parseInt(((nextMonth-FOM)/global_oneDay));

        // Work out what day of week the month ends on. THen work out how many blank entries
        // needed at end of calendar. Store this value in LDOMDayOffset
        var LDOM = new Date();
            LDOM.setFullYear(calendarYear,calendarMonth,FOMMonthLength);
            LDOMDayOffset=7-LDOM.getDay();
            if (LDOMDayOffset==7) {
                LDOMDayOffset=0;
            }

        // We store all the day values in an array
        // Note that blank days are stored as an empty string
        var calendarArray = new Array();
        // Firstly add the blank days at the start
        for (var counter=0; counter<FOMDayOffset; counter++) {
            calendarArray[calendarArray.length]="";
        }
        // Now add the actual days
        for (var counter2=0; counter2<FOMMonthLength; counter2++) {
            calendarArray[calendarArray.length]=(counter2+1);
        }
        // Finally add the blank days at the end
        for (var counter3=0; counter3<LDOMDayOffset; counter3++) {
            calendarArray[calendarArray.length]="";
        }

        // Now generate the HTML
        var insertHTML=""
        insertHTML+='<div class="controls-holder">';
        insertHTML+='<a href="#" class="select-previous-month">Previous month</a>';
        insertHTML+='<a href="#" class="select-next-month">Next month</a>';
        insertHTML+="<h5>"+monthsArray[FOM.getMonth()]+" "+calendarYear+"</h5>\n";
        insertHTML+='</div>';
        insertHTML+='<div class="calendar-table-holder">';
        insertHTML+="<table>\n";
        insertHTML+="<thead><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th class='weekend'>S</th><th class='weekend'>S</th></thead>";
        var numofrows=parseInt((calendarArray.length)/7);
        if ((calendarArray.length % 7) != 0) {
            numofrows++;
        }
        for (var weekrows=0; weekrows<numofrows; weekrows++) {
            insertHTML+="\t<tr>\n";
            for (var weekday=0; weekday<7;weekday++) {
                var highlight="";
                if (weekday>=5) {
                    highlight=' class="weekend" ';
                }
                if ((selectedYear==calendarYear) && (selectedMonth==calendarMonth) && selectedDay==(calendarArray[weekrows*7+weekday])) {
                    highlight=' class="selected" ';
                }
                insertHTML+="\t\t<td"+highlight+"><p>"+calendarArray[weekrows*7+weekday]+"</p>";
                insertHTML+='<span class="date-day">'+calendarArray[weekrows*7+weekday]+'</span>';
                var weekdaynumber=weekday+1;
                if (weekdaynumber==7) {
                    weekdaynumber=0;
                }
                insertHTML+='<span class="date-week-day">'+daysArray[weekdaynumber]+'</span>';
                insertHTML+='<span class="date-day-suffix">'+suffixArray[calendarArray[weekrows*7+weekday]-1]+'</span>';
                insertHTML+='<span class="date-month">'+calendarMonth+'</span>';
                insertHTML+='<span class="date-month-text">'+monthsArray[calendarMonth]+'</span>';
                insertHTML+='<span class="date-year">'+calendarYear+'</span>';
                insertHTML+="</td>\n";
            }
            insertHTML+="\t</tr>\n";
        }
        insertHTML+="</table>\n";
        insertHTML+="</div>\n";
        insertHTML+="<h6>"+daysArray[selectedWeekDay]+", <span>"+selectedDay+""+suffixArray[selectedDay]+" "+monthsArray[selectedMonth]+" "+selectedYear+"</span></h6>";
        $(insertelement).empty().append(insertHTML);
    }

    /* FUNCTION saveinitialwidgetstate by Alex Kearns
     *
     * This function saves the state of the widgets when a user first signs up.
     * The function also sets the id span of each widget
     * The function takes an optional callback function
     ************************************************************************************/
    var saveinitialwidgetstate = function(callback) {
        var widgetinfo="";
        var numofuserwidgets=$("div#drag-column-holder div.widget").length;
        for (var counter=0; counter<numofuserwidgets; counter++) {
            var thiswidget=$("div#drag-column-holder div.widget:eq("+counter+")");
            var tempposition=findWidgetPos($(thiswidget).get()[0]);
            var storedposition;
            if (tempposition[0]<10) {
                storedposition="0"+tempposition[0].toString();
            }
            else {
                storedposition=tempposition[0].toString();
            }
            if (tempposition[1]<10) {
                storedposition+="0"+tempposition[1].toString();
            }
            else {
                storedposition+=tempposition[1].toString();
            }
            var storedcolour=$(thiswidget).find("span.widget-info-colour").text();
            var storedtype=$(thiswidget).find("span.widget-info-type").text();
            var storedsetting=$(thiswidget).find("span.widget-info-setting").text();
            widgetinfo+=(global_widgettypes[storedtype]+"#"+storedposition+"#"+global_widgetcolours[storedcolour]+"#"+storedsetting);
            if ((counter+1)<numofuserwidgets) {
                widgetinfo+=",";
            }
        }
        $.post("/assets/ajax/state-save-initial.php", { userid:userId, widgetinfo:widgetinfo }, function(data) {
            for (var counter1=0; counter1<numofuserwidgets; counter1++) {
                $("div#drag-column-holder div.widget:eq("+counter1+") span.widget-info-id").text(data.split("#")[counter1]);
            }
            callback();
        });
    }


    /* FUNCTION updatemovedwidgets() by Alex Kearns
     *
     * This function finds widgets whose positions have moved.
     * And updates their positions in the database
     ************************************************************************************/
    var updatemovedwidgets = function() {
        var widgetmovedarray = new Array();
        $("div#drag-column-holder div.widget").each( function() {
            var actualposition=findWidgetPos(this);
            var expectedposition=$(this).find("span.widget-info-position").text().split("'");
            if (actualposition[0] !== expectedposition[0] || actualposition[1] !== expectedposition[1]) {
                var newposition=(actualposition[0]*100)+actualposition[1];
                $(this).find("span.widget-info-position").text(actualposition[0].toString()+","+actualposition[1].toString());
                widgetmovedarray[widgetmovedarray.length]=$(this).find("span.widget-info-id").text()+"#"+newposition.toString();
            }
        });
        var nummovedwidgets=widgetmovedarray.length;
        if (nummovedwidgets > 0) {
            var implodeddata="";
            for (counter=0; counter<nummovedwidgets; counter++) {
                if ((counter+1)==nummovedwidgets) {
                    implodeddata+=widgetmovedarray[counter];
                }
                else {
                    implodeddata+=widgetmovedarray[counter]+",";
                }
            }
            $.post("assets/ajax/state-update-positions.php", { widgetdata: implodeddata}, function(data) {
                // Maybe an error message here
            });
        }
    }


    /* FUNCTION updatewidgetotheme() by Alex Kearns
     *
     * This function updates the colour of the widgets to the current theme.
     * It also saves the currenttheme
     ************************************************************************************/

    var updatewidgetstotheme = function() {
    if (userId) {
        if (currentTheme != selectedTheme) {
            currentTheme = selectedTheme;
            $.post("assets/ajax/state-change-theme.php", { userid: userId, theme: currentTheme });
                var tempwidgetdata="";
                var tempnumwidgets=$("div#drag-column-holder div.widget").length;
                for (var counter=0; counter<tempnumwidgets; counter++) {
                    tempwidgetdata+=$("div#drag-column-holder div.widget:eq("+counter+")").find("span.widget-info-id").text();
                    tempwidgetdata+="#"+global_widgetcolours[$("div#drag-column-holder div.widget:eq("+counter+")").find("span.widget-info-colour").text()];
                    if ((counter+1) < tempnumwidgets) {
                        tempwidgetdata+=",";
                    }
                }
            $.post("assets/ajax/state-update-colours.php", { widgetinfo: tempwidgetdata });
            }
        }
    }


    /* POP UP LOGIN BOX by Alex Kearns
     *
     * This function opens a popup box for login in and registering with Shockwaves.
     ************************************************************************************************/
    var loginPopup = function(selectpanel) {
        // $("body").css({position:"absolute", overflow:"hidden"});
        $("body").css({overflow:"hidden"});
        var pageheight=getViewportDimensions()[1];
        if (pageheight < $("body").height()) {
            pageheight=$("body").height();
        }
        $("div#login-popup-fader").css({height:pageheight, width:$("body").width()});
        $("div#login-popup-fader").css({display:"block"});

        var displayErrorHighlightIfEmpty = function(inputelement) {
            if (!$(inputelement).val()) {
                $(inputelement).parent().addClass("error-highlight");
                return true;
            }
        return false;
        }

        // empty fields
        $("div#login-popup-holder").find("input").each( function() {
            if ($(this).attr("type")=="text" || $(this).attr("type")=="password") {
                $(this).val("");
            }
        });

        $("div#login-popup-holder").find("a.signup-tab").unbind().click( function() {
            $("div#login-popup-holder div.login-menu a").removeClass("selected");
            $(this).addClass("selected");
            $("div#login-popup-holder div.login-panel").css({display:"none"});
            $("div#login-popup-holder div.signup-panel").css({display:"block"});
            return false;
        });

        $("div#login-popup-holder").find("a.login-tab").unbind().click( function() {
            $("div#login-popup-holder div.login-menu a").removeClass("selected");
            $(this).addClass("selected");
            $("div#login-popup-holder div.signup-panel").css({display:"none"});
            $("div#login-popup-holder div.login-panel").css({display:"block"});
            return false;
        });


        $("div#login-popup-holder div.login-panel form").unbind().submit( function() {
            var thisajaxform=this;
            $("div#login-popup-holder div.login-panel").find("li.error-highlight").removeClass("error-highlight");
            $(this).find("p.error-message").empty().css({display:"none"});
            if ($(this).find("input.username").val() && $(this).find("input.password").val()) {
                var enteredusername=$(this).find("input.username").val();
                var enteredpassword=$(this).find("input.password").val();
                $.post("/assets/ajax/user-login.php", { username: enteredusername, password: enteredpassword }, function(xml) {
                    var ajaxsuccess=$(xml).find("success").text();
                    if (ajaxsuccess=="false") {
                        var ajaxerror=$(xml).find("error").text();

                        switch(ajaxerror) {
                            case "no user":
                                $(thisajaxform).find("p.error-message").text("Sorry, we could not find a user matching the username and password you entered. Please try again.").css({display:"block"});
                                $(thisajaxform).find("input.username").parent().addClass("error-highlight");
                                $(thisajaxform).find("input.password").parent().addClass("error-highlight");
                            break;

                            case "missing fields":
                                $(thisajaxform).find("p.error-message").text("There was an error with your submission. Please check that you have filled everything in correctly and try again.").css({display:"block"});

                            break;
                        }
                    }
                    else {
                        userId=$(xml).find("userid").text();
                        userName=$(xml).find("username").text();
                        var cookievalue=userId+"#$%"+userName;
                        Set_Cookie('shockwaves', cookievalue, 30, '/', '', '' );
                        // $("div#main-login-holder p.logged-in span").text(userName);
                        // $("div#main-login-holder p.logged-in").css({display:"block"});
                        // $("div#main-login-holder a.sign-in").css({display:"none"});
                        // $("div#login-popup-holder div.signup-panel").css({display:"none"});

                        // $("div#login-popup-holder div.login-popup-inner div.close-button").click();
                        window.location.reload(true);
                    // Load users page;
                    }
                });

            }
            else if($(this).find("input.forgotten-login").val()){
                var enteredemail=$(this).find("input.forgotten-login").val();
                $.post("/assets/ajax/generate-password.php", { email: enteredemail }, function(xml) {
                    if(xml == "success"){
                        $(this).find("p.email-sent-message").text("You will shortly receive an email containing your username and password.").css({display: "block"});
                    }
                    else {
                        $(this).find("p.email-sent-message").text("Sorry, there was a problem. Check your email and try again").css({display: "block"});
                    }
                })
            }
            else {
                // At least one field is empty. So display error message and highlight missing fields
                var errors=0;
                if (displayErrorHighlightIfEmpty($(this).find("input.username"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("input.password"))) {
                    errors++;
                }
                if (errors>1) {
                    $(this).find("p.error-message").text("There were errors with the highlighted fields. Please check you have filled everything in correctly and try again.").css({display:"block"});
                }
                else {
                    $(this).find("p.error-message").text("There was an error with the highlighted field. Please check you have filled everything in correctly and try again.").css({display:"block"});
                }
            }
        return false;
        });

        $("div#login-popup-holder div.signup-panel form").unbind().submit( function() {
            var thisajaxform=this;
            var optin="no";
            $("div#login-popup-holder div.signup-panel").find("li.error-highlight").removeClass("error-highlight");
            $(this).find("p.error-message").empty().css({display:"none"});
            if ($(this).find("input.username").val() && $(this).find("input.password").val() && $(this).find("input.email").val() && $(this).find("select.dob-day").val() && $(this).find("select.dob-month").val() && $(this).find("select.dob-year").val() && $(this).find("select.reg-sex").val()) {
                // All fields have been entered so submit sign up ajax

                if ($("div#login-popup-holder div.signup-panel input.marketing-optin-yes").attr("checked")) {
                    optin="yes";
                }
                var regage=$(this).find("select.dob-day").val()+" ";
                regage+=($(this).find("select.dob-month").val()+" ");
                regage+=$(this).find("select.dob-year").val();
                var regsex=$(this).find("select.reg-sex").val();
                $.post("/assets/ajax/user-signup.php", { username: $(this).find("input.username").val(), password: $(this).find("input.password").val(), email: $(this).find("input.email").val(), optin: optin, regage:regage,regsex: regsex  }, function(xml) {
                    var ajaxsuccess=$(xml).find("success").text();

                    if (ajaxsuccess=="false") {
                        var ajaxerror=$(xml).find("error").text();

                        switch(ajaxerror) {
                            case "username taken":
                                $(thisajaxform).find("p.error-message").text("Sorry, the username you entered has already been taken. Please enter a new username.").css({display:"block"});
                                $(thisajaxform).find("input.username").parent().addClass("error-highlight");
                            break;

                            case "missing fields":
                                $(thisajaxform).find("p.error-message").text("There was an error with your submission. Please check that you have filled everything in correctly and try again.").css({display:"block"});

                            break;
                        }
                    }
                    else { //Register successs
                        // Now save current widget state
                        var ajaxusername=$(xml).find("username").text();
                        var ajaxuserid=parseInt($(xml).find("userid").text());
                        userId=ajaxuserid;
                        userName=ajaxusername;
                        saveinitialwidgetstate( function() {
                            // Now display success
                            $("div#login-popup-holder div.signup-panel").css({display:"none"});
                            $("div#login-popup-holder div.success-panel").css({display:"block"});
                            var cookievalue=ajaxuserid+"#$%"+ajaxusername;
                            Set_Cookie('shockwaves', cookievalue, 30, '/', '', '' );
                            $("div#main-login-holder p.logged-in span").text(userName);
                            $("div#main-login-holder p.logged-in").css({display:"block"});
                            $("div#main-login-holder a.sign-in").css({display:"none"});
                            // Lets also save their if they have selected one
                            if (selectedTheme !="") {
                                updatewidgetstotheme();
                            }
                        });
                    }
                });
            }
            else {
                // At least one field is empty. So display error message and highlight missing fields
                var errors=0;
                if (displayErrorHighlightIfEmpty($(this).find("input.username"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("input.password"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("input.email"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("select.dob-day"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("select.dob-month"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("select.dob-year"))) {
                    errors++;
                }
                if (displayErrorHighlightIfEmpty($(this).find("select.reg-sex"))) {
                    errors++;
                }
                if (errors>1) {
                    $(this).find("p.error-message").text("There were errors with the highlighted fields. Please check you have filled everything in correctly and try again.").css({display:"block"});
                }
                else {
                    $(this).find("p.error-message").text("There was an error with the highlighted field. Please check you have filled everything in correctly and try again.").css({display:"block"});
                }
            }
        return false;
        });

        // Close button
        $("div#login-popup-holder a.close-tab").unbind().click( function() {
            $("div#login-popup-holder").css({display:"none"});
            $("div#login-popup-holder").find("li.error-highlight").removeClass("error-highlight");
            $("div#login-popup-holder").find("p.error-message").empty({display:"none"});
            $("div#login-popup-fader").css({display:"none"});
            $("body").css({position:"static", overflow:"auto"});
            return false;
        });

        $("div#login-popup-holder div.success-panel input.start-creating-button").click( function() {
            $("div#login-popup-holder a.close-tab").click();
            return false;
        });


        $("div#login-popup-holder div.login-popup-inner").css("margin-top",(150+pageScrollY())+"px");
        $("div#login-popup-holder div.login-panel").css({display:"none"});
        $("div#login-popup-holder div.signup-panel").css({display:"none"});
        $("div#login-popup-holder div.success-panel").css({display:"none"});
           $("div#login-popup-holder div.login-menu a").removeClass("selected");
        if (selectpanel) {
            $("div#login-popup-holder div."+selectpanel).css({display:"block"});
            if (selectpanel=="login-panel") {
                $("div#login-popup-holder div.login-menu a.login-tab").addClass("selected");
            }
            else {
                $("div#login-popup-holder div.login-menu a.signup-tab").addClass("selected");
            }
        }
        else {
            $("div#login-popup-holder div.login-panel").css({display:"block"});
            $("div#login-popup-holder div.login-menu a.login-tab").addClass("selected");
        }
        $("div#login-popup-holder").find("li.error-highlight").removeClass("error-highlight");
        $("div#login-popup-holder").css({height: $("body").height()+"px", width: $("body").width()+"px", display:"block"});

    }




    /* BOUND FUNCTION: initialisePromotionWidget() by Alex Kearns
     *
     * This funciton is bound to all Welcome widgets. It automatically sets up all the
     * controls, ajax calls, etc for a particular Welcome widget. Welcome widgets
     * should have this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.product-promotion-widget-holder").each( initialisePromotionWidget = function() {
        var thispromotionwidget=this;
        var currentpromotionimage=0;
        var numproducts=$(this).find("div.promotion-gallery-stage div.product-promotion").length;
        var swappingstopped=false;
        var currentlyswapping=false;
        var loadnewproduct;
        var parentWidget=$(this).parent().parent();

        // Initialisation

        $(thispromotionwidget).find("div.promotion-gallery-stage div.product-promotion").each( function() {
            $(this).find("div.hold-graphic").css({background: "url(/assets/ui/product-selector/"+$(this).find("span.hold-graphic").text()+")"});
            $(this).find("h4").css({color: "#"+$(this).find("span.headline-colour").text()});
        });


        $(this).find("p.current-product-number").text("1 of "+numproducts);

        $(this).find("span.minimise-function").click( function() {
            swappingstopped=true;
        });

        $(this).find("span.unminimise-function").click( function() {
            swappingstopped=false;
        });

        $(this).find("span.drag-function").click( function() {
            swappingstopped=true;
        });

        $(this).find("span.drop-function").click( function() {
            swappingstopped=false;
        });


        $(this).find("div.main-promotion-product").click( function() {
            var producturl=$(thispromotionwidget).find("div.product-promotion:eq("+currentpromotionimage+") span.product-link").text();
            window.open(producturl);
        });

        $(this).find("a.more").click( function() {
            window.open("/products/");
            return false;
        });

        setTimeout( loadnewproduct=function() {
            if(swappingstopped || currentlyswapping) {
                setTimeout( function() {
                    loadnewproduct();
                }, 5000);
                return false;
            }
            currentlyswapping=true;
            currentpromotionimage++;

            if (currentpromotionimage == numproducts) {
                currentpromotionimage=0;
            }
            $(thispromotionwidget).find("p.current-product-number").text((currentpromotionimage+1)+" of "+numproducts);
            var gallerywidth=$(thispromotionwidget).find("div.main-promotion-product").width();
            var galleryheight=$(thispromotionwidget).find("div.main-promotion-product").height();
            $(thispromotionwidget).find("div.promotion-gallery-stage").css({ width:gallerywidth});
            $(thispromotionwidget).find("div.promotion-gallery-stage").css({top:(-galleryheight*currentpromotionimage)});
            $(thispromotionwidget).find("div.main-promotion-product").animate({opacity: 0}, 500, function() {
                var newpromotionimage=$(thispromotionwidget).find("div.promotion-gallery-stage img:eq("+currentpromotionimage+")").attr("src");
                var oldpromotionimage=$(this).find("img.promotion-gallery-main-image").attr("src");
                if (newpromotionimage != oldpromotionimage) {
                    $(this).find("img.promotion-gallery-main-image").attr("src", newpromotionimage);
                }
                $(this).find("h5").text($(thispromotionwidget).find("div.promotion-gallery-stage h5:eq("+currentpromotionimage+")").text());
                $(this).find("h4").text($(thispromotionwidget).find("div.promotion-gallery-stage h4:eq("+currentpromotionimage+")").text()).css({color: "#"+$(thispromotionwidget).find("div.promotion-gallery-stage span.headline-colour:eq("+currentpromotionimage+")").text()});
                $(this).find("h6").text($(thispromotionwidget).find("div.promotion-gallery-stage h6:eq("+currentpromotionimage+")").text());
                $(this).find("p").text($(thispromotionwidget).find("div.promotion-gallery-stage p:eq("+currentpromotionimage+")").text());
                $(this).find("div.hold-graphic").css({background: "url(/assets/ui/product-selector/"+$(thispromotionwidget).find("div.promotion-gallery-stage span.hold-graphic:eq("+currentpromotionimage+")").text()+")"});
                var mainpromotionproduct=this;
                setTimeout(function() {
                    $(mainpromotionproduct).css({opacity: 1});
                }, 150);
                currentlyswapping=false;

                // Make sure future images are loaded
                if ((currentpromotionimage+1) <numproducts) {
                    var newimagesrc=$(thispromotionwidget).find("div.promotion-gallery-stage span.image-src:eq("+(currentpromotionimage+1)+")").text();
                    $(thispromotionwidget).find("div.promotion-gallery-stage img:eq("+(currentpromotionimage+1)+")").attr("src", newimagesrc);
                }

                setTimeout( function() {
                    loadnewproduct();
                }, 5000);
            });
        }, 10000);

    });



    /* BOUND FUNCTION: initialiseWelcomeWidget() by Alex Kearns
     *
     * This funciton is bound to all Welcome widgets. It automatically sets up all the
     * controls, ajax calls, etc for a particular Welcome widget. Welcome widgets
     * should have this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.welcome-widget-holder").each( initialiseWelcomeWidget = function() {
        $(this).find("a.sign-me-up").click( function() {
            loginPopup("signup-panel");
            return false;
        });

        $(this).find("a.show-me-modules").click( function() {
            if (currentlySelectedPanel != "modules") {
                $("div#widget-selection-holder a.modules-selection-tab").click();
            }
            return false;
        });

        $(this).find("a.show-me-themes").click( function() {
            if (currentlySelectedPanel != "themes") {
                $("div#widget-selection-holder a.themes-selection-tab").click();
            }
            return false;
        });
    });

    /* BOUND FUNCTION: initialiseMusicReviewsWidget() by Alex Kearns
     *
     * This funciton is bound to all NME Music Reviews widgets. It automatically sets up all the
     * controls, ajax calls, etc for a particular Music Reviews widget. New Music Review widgets
     * should have this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.music-reviews-widget-holder").each( initialiseMusicReviewsWidget = function() {
        var thismusicreviews=this;
        var pagenum=1;
        var currentlyloading=false;
        var totalnumofreviews=0;

        $(thismusicreviews).find("div.control-holder a.previous-button").css({opacity: 0.3});

        var loadMusicReviews=function() {
            currentlyloading=true;
            $(thismusicreviews).find("div.stage-inner-inner").css({opacity: 0.25});
            insertWidgetAjaxLoader(thismusicreviews);

            $.post("/assets/ajax/music-reviews-widget-get-reviews.php", { pagenum: pagenum }, function(xml) {
                var numofxmlreviews=$(xml).find("review").length;
                if (numofxmlreviews == 0) {
                    $(thismusicreviews).find("div.control-holder a.next-button").css({opacity: 0.3});
                    pagenum--;
                    if (pagenum<1) {
                        pagenum=1;
                    }
                }
                else {
                    var insertHTML="";
                    for (var counter=0; counter<numofxmlreviews; counter++) {
                        insertHTML+='<div class="music-reviews-block">';
                        insertHTML+='<img src="'+$(xml).find("image-src:eq("+counter+")").text()+'" alt="" class="reflect" />';
                        insertHTML+='<h3>'+$(xml).find("review-type:eq("+counter+")").text()+'</h3>';
                        insertHTML+='<h4 class="widget-colour">'+$(xml).find("band:eq("+counter+")").text()+'</h4>';
                        insertHTML+='<h5>'+$(xml).find("album:eq("+counter+")").text()+'</h5>';
                        insertHTML+='<p>'+$(xml).find("description:eq("+counter+")").text()+'</p>';
                        insertHTML+='<p class="more">Read more>></p>';
                        insertHTML+='<span class="music-reviews-url">'+$(xml).find("link:eq("+counter+")").text()+'</span>';
                        insertHTML+='<div class="clear"></div>';
                        insertHTML+='</div>';
                    }
                    $(thismusicreviews).find("div.music-reviews-holder").empty().append(insertHTML);
                    $(thismusicreviews).find("div.music-reviews-block").click( function() {
                        window.open($(this).find("span.music-reviews-url").text());
                    });
                    $(this).find("div.control-holder p").text(pagenum+" of "+totalnumofreviews);
                    /* Reflection.add($(this).find("div.music-reviews-block img").get()[0]); */
                }
                precalculateWidgetCoords();
                removeWidgetAjaxLoader(thismusicreviews);
                $(thismusicreviews).find("div.stage-inner-inner").css({opacity: 1});
                currentlyloading=false;
            });
        }
        $.get("assets/ajax/music-reviews-widget-get-num.php",{}, function(data) {
            totalnumofreviews=data;
            loadMusicReviews();
        });

        $(this).find("div.control-holder a.previous-button").click( function() {
            if (currentlyloading) {
                return false;
            }
            pagenum--;
            if (pagenum<1) {
                pagenum=1;
                $(this).css({opacity: 0.3});
                return false;
            }
            loadMusicReviews();
            $(thismusicreviews).find("div.control-holder a.next-button").css({opacity: 1});
            return false;
        });

        $(this).find("div.control-holder a.next-button").click( function() {
            if (currentlyloading) {
                return false;
            }
            pagenum++;
            $(thismusicreviews).find("div.control-holder a.previous-button").css({opacity: 1});
            loadMusicReviews();
            return false;
        });

    });

    /* BOUND FUNCTION: initialiseMusicNewsWidget() by Alex Kearns
     *
     * This funciton is bound to all NME Music News widgets. It automatically sets up all the
     * controls, ajax calls, etc for a particular Music News widget. New Music widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.music-news-widget-holder").each( initialiseMusicNewsWidget = function() {
        var thismusicnews=this;
        var pagenum=1;
        var currentlyloading=false;

        $(thismusicnews).find("div.control-holder a.previous-button").css({opacity: 0.3});

        var loadMusicNews=function() {
            currentlyloading=true;
            $(thismusicnews).find("div.stage-inner-inner").css({opacity: 0.25});
            insertWidgetAjaxLoader(thismusicnews);
            $.post("/assets/ajax/nme-news-widget-get-news.php", { pagenum: pagenum }, function(xml) {
                var numofxmlnews=$(xml).find("news-item").length;
                if (numofxmlnews == 0) {
                    $(thismusicnews).find("div.control-holder a.next-button").css({opacity: 0.3});
                    pagenum--;
                    if (pagenum<1) {
                        pagenum=1;
                    }
                }
                else {
                    var insertHTML="";
                    for (var counter=0; counter<numofxmlnews; counter++) {
                        insertHTML+='<div class="music-news-block">';
                        insertHTML+='<img src="'+$(xml).find("image-src:eq("+counter+")").text()+'" alt="" />';
                        insertHTML+='<h4>'+$(xml).find("band:eq("+counter+")").text()+'</h4>';
                        insertHTML+='<h5 class="widget-colour">'+$(xml).find("title:eq("+counter+")").text()+'</h5>';
                        insertHTML+='<p>'+$(xml).find("description:eq("+counter+")").text()+'</p>';
                        insertHTML+='<p class="more">Read more>></p>';
                        insertHTML+='<span class="music-news-url">'+$(xml).find("link:eq("+counter+")").text()+'</span>';
                        insertHTML+='<div class="clear"></div>';
                        insertHTML+='</div>';
                    }
                    $(thismusicnews).find("div.music-news-holder").empty().append(insertHTML);
                    $(thismusicnews).find("div.music-news-block").click( function() {
                        window.open($(this).find("span.music-news-url").text());
                    });
                }
                precalculateWidgetCoords();
                removeWidgetAjaxLoader(thismusicnews);
                $(thismusicnews).find("div.stage-inner-inner").css({opacity: 1});
                currentlyloading=false;
            });
        }
        loadMusicNews();

        $(this).find("div.control-holder a.previous-button").click( function() {
            if (currentlyloading) {
                return false;
            }
            pagenum--;
            if (pagenum<1) {
                pagenum=1;
                $(this).css({opacity: 0.3});
                return false;
            }
            loadMusicNews();
            $(thismusicnews).find("div.control-holder a.next-button").css({opacity: 1});
            return false;
        });

        $(this).find("div.control-holder a.next-button").click( function() {
            if (currentlyloading) {
                return false;
            }
            pagenum++;
            $(thismusicnews).find("div.control-holder a.previous-button").css({opacity: 1});
            loadMusicNews();
            return false;
        });

    });

    /* BOUND FUNCTION: initialiseCoolLinksWidget() by Alex Kearns
     *
     * This funciton is bound to all Style, Attract Play widgets. It automatically sets up all the
     * controls, ajax calls, etc for a particular Cool Links element. New Cool Link widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.cool-links-widget-holder").each( initialiseCoolLinksWidget = function() {
        var thiscoollinks=this;
        var pagenum=1;
        var currentlyloading=false;

        $(thiscoollinks).find("div.control-holder a.previous-button").css({opacity: 0.3});

        var loadLinks=function() {
            currentlyloading=true;
            $(thiscoollinks).find("div.stage-inner-inner").css({opacity: 0.25});
            insertWidgetAjaxLoader(thiscoollinks);
            $.post("/assets/ajax/cool-links-widget-get-links.php", { pagenum: pagenum }, function(xml) {
                var numofxmllinks=$(xml).find("cool-link").length;
                if (numofxmllinks == 0) {
                    $(thiscoollinks).find("div.control-holder a.next-button").css({opacity: 0.3});
                    pagenum--;
                    if (pagenum<1) {
                        pagenum=1;
                    }
                }
                else {
                    var insertHTML="";
                    for (var counter=0; counter<numofxmllinks; counter++) {
                        insertHTML+='<div class="cool-link-block">';
                        insertHTML+='<img src="'+$(xml).find("image-src:eq("+counter+")").text()+'" alt="" />';
                        insertHTML+='<h4>'+$(xml).find("title:eq("+counter+")").text()+'</h4>';
                        insertHTML+='<p>'+$(xml).find("description:eq("+counter+")").text()+'</p>';
                        insertHTML+='<span class="cool-link-url">'+$(xml).find("link:eq("+counter+")").text()+'</span>';
                        insertHTML+='<div class="clear"></div>';
                        insertHTML+='</div>';
                    }
                    $(thiscoollinks).find("div.cool-links-holder").empty().append(insertHTML);
                    $(thiscoollinks).find("div.cool-link-block").click( function() {
                        window.open($(this).find("span.cool-link-url").text());
                    });
                }
                precalculateWidgetCoords();
                removeWidgetAjaxLoader(thiscoollinks);
                $(thiscoollinks).find("div.stage-inner-inner").css({opacity: 1});
                currentlyloading=false;

            });
        }
        loadLinks();

        $(this).find("div.control-holder a.previous-button").click( function() {
            if (currentlyloading) {
                return false;
            }
            pagenum--;
            if (pagenum<1) {
                pagenum=1;
                $(this).css({opacity: 0.3});
                return false;
            }
            loadLinks();
            $(thiscoollinks).find("div.control-holder a.next-button").css({opacity: 1});
            return false;
        });

        $(this).find("div.control-holder a.next-button").click( function() {
            if (currentlyloading) {
                return false;
            }
            pagenum++;
            $(thiscoollinks).find("div.control-holder a.previous-button").css({opacity: 1});
            loadLinks();
            return false;
        });

    });



    /* BOUND FUNCTION: initialiseVideoGallery() by Alex Kearns
     *
     * This funciton is bound to all video gallery widgets. It automatically sets up all the video specific,
     * controls, ajax calls, etc for a particular video gallery element. New video gallery widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.video-gallery-holder").each( initialiseVideoGallery = function() {
        var parentWidget=$(this).parent();
        var thisvideogallery=this;
        var loadnewgallery="";
        var pagenum=1;
        var searchterm=$(parentWidget).parent().find("span.widget-info-setting").text();
        var lastimagesrc="";
        var previoussearchterm=$(parentWidget).parent().find("span.widget-info-setting").text();
        var numofvideos=0;
        var thiswidgetid=$(parentWidget).parent().find("span.widget-info-id").text();

        $(this).find("form.create-gallery").submit( loadnewgallery=function() {
            var lastcontainerheight=150;
            var thumbnailwidth=79; // This actually the height of the thumbnail in this gallery
            var carouselscrolling=false;
            var alreadyloaded="";
            var stillloadingnewimages=false;
            var leftmostthumb=0;
            var initialisethumbnails;


            if (isIE || isFireFox) {
                $(thisvideogallery).find("div.carousel-stage").css("margin-top","0");
            }
            else {
                $(thisvideogallery).find("div.carousel-stage").css("margin-top","-1000px"); // Needed for Safari
                $(thisvideogallery).find("div.carousel-stage").css("margin-top","-1px"); // Needed for Safari
            }
            if (searchterm=$(this).find("input.gallery-searchterm").attr("value")) {
                $(parentWidget).parent().find("span.widget-info-setting").text(searchterm);
                searchterm=searchterm.replace(" ","+");
                $(thisvideogallery).find("div.video-embed-holder span div").css({visibility: "hidden"});
                $(thisvideogallery).find("div.stage-inner-inner").css({opacity: 0.25});
                insertWidgetAjaxLoader(thisvideogallery);

                $.post("/assets/ajax/getyoutubevids.php", { searchterm: searchterm, pagenum: pagenum }, function(xml) {
                    var numofxmlvideos=$(xml).find("video").length;
                    if (numofxmlvideos==0) {
                        searchterm=previoussearchterm;
                        $(this).find("input.gallery-searchterm").attr("value",searchterm);
                        $(thisvideogallery).find("div.video-embed-holder span div").css({visibility: "visible"});
                        removeWidgetAjaxLoader(thisvideogallery);
                        insertWidgetErrorMessage(thisvideogallery,"Sorry, we couldn't find any videos matching the search term you entered. Please go to the settings option in this widget's menu, and try a new search term");
                        return false;
                    }
                    thiswidgetid=$(parentWidget).parent().find("span.widget-info-id").text();
                    if ((previoussearchterm != searchterm) && thiswidgetid) {
                        $.post("assets/ajax/state-update-settings.php", { newsetting: searchterm, widgetid: thiswidgetid}, function(data) {
                            // Maybe display error message if necessary
                        });
                    }
                    previoussearchterm=searchterm;
                    numofvideos=0;
                    leftmostthumb=0;
                    pagenum=1;
                    lastimagesrc="";
                    $(thisvideogallery).find("*").unbind();

                    $(thisvideogallery).find("span.minimise-function").click( function() {
                        if(!isIE) {
                            $(thisvideogallery).find("div.video-embed-holder").css({visibility: "hidden"});
                        }
                    });

                    $(thisvideogallery).find("span.unminimise-function").click( function() {
                        if(!isIE) {
                            $(thisvideogallery).find("div.video-embed-holder").css({visibility: "visible"});
                        }
                    });

                    $(thisvideogallery).find("span.kill-function").click( function() {
                        if(!isIE) {
                            $(thisvideogallery).find("div.video-embed-holder").css({visibility: "hidden"});
                        }
                    });

                    $(thisvideogallery).find("a.customise-it").click( function() {
                        $(parentWidget).find("div.options-holder li").css({display:"none"});
                        $(parentWidget).find("div.options-holder li:eq(0)").css({display:"block"});
                        var newheight = specialFindHeight($(parentWidget).find("div.options-holder div.options-holder-inner"),$(parentWidget).width()-26);
                        $(parentWidget).find("div.options-holder").css({display: "block"}).animate({height: newheight+40},500, function() {});
                        return false;
                    });

                    numofvideos+=numofxmlvideos;
                    var insertHTML="";
                    for (var counter=0; counter<numofxmlvideos; counter++) {
                        insertHTML+='<div class="carousel-video-block">'
                        insertHTML+='<img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("code:eq("+counter+")").text()+'" />';
                        insertHTML+="<h4 class='widget-colour-light'>"+trimToMaxCharWords($(xml).find("headline:eq("+counter+")").text().toProperCase(),20)+"</h4>";
                        insertHTML+="<p>"+trimToMaxCharWords($(xml).find("description:eq("+counter+")").text(),60)+"</p>";
                        insertHTML+="<h5>Time: "+$(xml).find("time:eq("+counter+")").text()+"</h5>";
                        insertHTML+='</div>'
                    }
                    $(thisvideogallery).find("div.video-embed-holder span").css({display:"none"});
                    if (!isIE) {
                        $(thisvideogallery).find("div.video-embed-holder span").css({display:"block"});
                    }
                    $(thisvideogallery).find("div.carousel-stage").empty().append(insertHTML);
                    $(thisvideogallery).find("div.video-embed-holder").css({height: parseInt($(thisvideogallery).find("div.video-embed-holder").width()*350/425)});


                    $(thisvideogallery).find("div.video-embed-holder span").html('<div><object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'+$(xml).find("code:eq(0)").text()+'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+$(xml).find("code:eq(0)").text()+'" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></div>');

                    if (isFireFox) {
                            $(thisvideogallery).find("div.video-embed-holder div").css({height: parseInt($(thisvideogallery).find("div.video-embed-holder").height())});
                    }

                    if (isIE) {
                        setTimeout(function() {
                            $(thisvideogallery).find("div.video-embed-holder span").css({display: "block"});
                        },100);
                    }

                    // Needed because size of element has changed;
                    setTimeout(function() {
                        removeWidgetAjaxLoader(thisvideogallery);
                        $(thisvideogallery).find("div.stage-inner-inner").css({opacity: 1});
                        precalculateWidgetCoords();
                    }, 1000);

                    $(thisvideogallery).find("form.create-gallery").css({display:"none"});
                    $(thisvideogallery).find("div.carousel-holder").css({display: "block"});
                    lastimagesrc=$(thisvideogallery).find("div.carousel-stage img:eq(0)").attr("name").split("#")[0];
                    var currentlyRotating=false;
                    initialisethumbnails = function(thisgallery) {
                        $(thisgallery).find("div.carousel-stage img").unbind().click( function() {
                            if (currentlyRotating==true) {
                                return;
                            }
                            /* var clickedimage=this;
                            var newimagesrc=$(clickedimage).attr("name").split("#")[0];
                            if (newimagesrc==lastimagesrc) {
                                return;
                            }
                            lastimagesrc=newimagesrc; */
                            // currentlyRotating=true;
                            if (isIE) {
                                $(thisgallery).find("div.video-embed-holder span").css({display: "none"});
                            }
                            $(thisgallery).find("div.video-embed-holder span").empty();
                            $(thisgallery).find("div.video-embed-holder").css({height: parseInt($(thisgallery).find("div.video-embed-holder").width()*350/425)});

                            $(thisgallery).find("div.video-embed-holder span").html('<div><object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'+$(this).attr("name")+'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+$(this).attr("name")+'" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></div>');

                            if (isFireFox) {
                                    $(thisvideogallery).find("div.video-embed-holder div").css({height: parseInt($(thisvideogallery).find("div.video-embed-holder").height())});
                            }

                            if (isIE) {
                                setTimeout(function() {
                                    $(thisgallery).find("div.video-embed-holder span").css({display: "block"});
                                },100);
                            }
                            return false;
                        });
                    }
                    initialisethumbnails(thisvideogallery);
                    $(thisvideogallery).find("div.carousel-holder a.right-button").click( function() {
                        var loadingnewthumbs=false;
                        if (carouselscrolling) {
                            return false;
                        }
                        carouselscrolling=true;
                        var displayedthumbnails=parseInt($(this).parent().find("div.carousel").width()/thumbnailwidth);
                        displayedthumbnails=3;
                        var newleftmostthumb=leftmostthumb+displayedthumbnails;
                        if (newleftmostthumb>=(numofvideos-displayedthumbnails)) {
                            newleftmostthumb=(numofvideos-displayedthumbnails);
                            loadingnewthumbs=true;
                        }
                        if (displayedthumbnails>numofvideos) {
                            newleftmostthumb=0;
                        }
                        leftmostthumb=newleftmostthumb;
                        if (stillloadingnewimages) {
                            carouselscrolling=false;
                        }
                        else {
                            stillloadingnewimages=true;
                            $(thisvideogallery).find("div.carousel-stage").animate({marginTop: -(leftmostthumb*thumbnailwidth)}, 1000, function() {
                                if (loadingnewthumbs) {
                                    pagenum++;
                                    $.post("/assets/ajax/getyoutubevids.php", { searchterm: searchterm, pagenum: pagenum }, function(xml) {
                                        var insertHTML="";
                                        var numofxmlvideos2=$(xml).find("video").length;
                                        if ($(xml).find("thumb-src:eq(0)").text()==$(thisvideogallery).find("div.carousel-stage img:eq(0)").attr("src")) {
                                            pagenum--;
                                            stillloadingnewimages=false;
                                            return false;
                                        }
                                        numofvideos=numofvideos+numofxmlvideos2;
                                        // var insertHTML="";
                                        for (var counter=0; counter<numofxmlvideos; counter++) {
                                            insertHTML+='<div class="carousel-video-block">'
                                            insertHTML+='<img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("code:eq("+counter+")").text()+'" />';
                                            insertHTML+="<h4 class='widget-colour-light'>"+trimToMaxCharWords($(xml).find("headline:eq("+counter+")").text().toProperCase(),20)+"</h4>";
                                            insertHTML+="<p>"+trimToMaxCharWords($(xml).find("description:eq("+counter+")").text(),60)+"</p>";
                                            insertHTML+="<h5>Time: "+$(xml).find("time:eq("+counter+")").text()+"</h5>";
                                            insertHTML+='</div>'
                                        }
                                        $(thisvideogallery).find("div.carousel-stage").append(insertHTML);
                                        initialisethumbnails(thisvideogallery);
                                        stillloadingnewimages=false;
                                    });
                                }
                                else {
                                    stillloadingnewimages=false;
                                }
                                carouselscrolling=false;
                            });
                        }
                        return false;
                    });

                    $(thisvideogallery).find("div.carousel-holder a.left-button").click( function() {
                        if (carouselscrolling) {
                            return false;
                        }
                        carouselscrolling=true;
                        var displayedthumbnails=parseInt($(this).parent().find("div.carousel").width()/thumbnailwidth);
                        displayedthumbnails=3;
                        var newleftmostthumb=leftmostthumb-displayedthumbnails;
                        if (newleftmostthumb<0) {
                            newleftmostthumb=0;
                        }
                        leftmostthumb=newleftmostthumb;
                        $(thisvideogallery).find("div.carousel-stage").animate({marginTop: -(leftmostthumb*thumbnailwidth)}, 1000, function() {
                            $(this).css({left: (-(leftmostthumb*thumbnailwidth))});
                            carouselscrolling=false;
                        });
                        return false;
                    });

                });
            }
            else {
                // error message;
            }
        return false;
        });
        $(parentWidget).find("div.options-holder form.create-gallery").bind("submit", loadnewgallery);
        $(parentWidget).find("div.options-holder form.create-gallery").submit(function() {
            $(parentWidget).find("a.options-close-button").click();
        });
        // Load initial video gallery
        $(parentWidget).find("div.options-holder form.create-gallery input.gallery-searchterm").val($(parentWidget).parent().find("span.widget-info-setting").text());
        $(parentWidget).find("div.options-holder form.create-gallery").submit();
    });



    /* BOUND FUNCTION: initialiseDouglasGallery() by Alex Kearns
     *
     * This funciton is bound to all Douglas gallery widgets. It automatically sets up all the video specific,
     * controls, ajax calls, etc for a particular douglas gallery element. New douglas gallery widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.douglas-gallery-holder").each( initialiseDouglasGallery = function() {
        var parentWidget=$(this).parent();
        var thisvideogallery=this;
        var loadnewgallery="";
        $(this).find("form.create-gallery").submit( loadnewgallery=function() {
            $(thisvideogallery).find("*").unbind();
            var lastcontainerheight=150;
            var leftmostthumb=0;
            var numofvideos=0;
            var thumbnailwidth=79; // This actually the height of the thumbnail in this gallery
            var carouselscrolling=false;
            var pagenum=1;
            var searchterm="";
            var alreadyloaded="";
            var lastimagesrc="";
            var stillloadingnewimages=false;

            $(thisvideogallery).find("span.minimise-function").click( function() {
                if(!isIE) {
                    $(thisvideogallery).find("div.video-embed-holder").css({visibility: "hidden"});
                }
            });

            $(thisvideogallery).find("span.unminimise-function").click( function() {
                if(!isIE) {
                    $(thisvideogallery).find("div.video-embed-holder").css({visibility: "visible"});
                }
            });

            $(thisvideogallery).find("span.kill-function").click( function() {
                if(!isIE) {
                    $(thisvideogallery).find("div.video-embed-holder").css({visibility: "hidden"});
                }
            });


            $(thisvideogallery).find("div.douglas-blurb a").click(function() {
                window.open($(this).attr("href"));
                return false;
            });

            var updateCarouselDisplayImages = function() {
                for (var counter=0; counter<4; counter++) {
                    var selecteddisplayimage=$(thisvideogallery).find("div.carousel-displayed-images img:eq("+counter+")");
                    var selectedcarouselimage=$(thisvideogallery).find("div.carousel-stage img:eq("+(counter+leftmostthumb)+")");
                    if (selectedcarouselimage.length) {
                        $(selecteddisplayimage).css({display:"block"})
                        $(selecteddisplayimage).attr("src", $(selectedcarouselimage).attr("src"))
                        $(selecteddisplayimage).attr("name", $(selectedcarouselimage).attr("name"))
                    }
                    else {
                        $(selecteddisplayimage).css({display:"none"})
                    }
                }
            }


            if (isIE || isFireFox) {
                $(thisvideogallery).find("div.carousel-stage").css("margin-top","0");
            }
            else {
                $(thisvideogallery).find("div.carousel-stage").css("margin-top","-1000px"); // Needed for Safari
                $(thisvideogallery).find("div.carousel-stage").css("margin-top","-1px"); // Needed for Safari
            }

            if (searchterm=$(this).find("input").attr("value")) {
                searchterm=searchterm.replace(" ","+");
                $(thisvideogallery).find("div.stage-inner-inner").css({opacity: 0.25});
                insertWidgetAjaxLoader(thisvideogallery);

                $.post("/assets/ajax/getyoutubevids.php", { searchterm: searchterm, pagenum: pagenum }, function(xml) {
                    var numofxmlvideos=$(xml).find("video").length;
                    $(thisvideogallery).find("p.error-message").css({display:"none"});
                    if (numofxmlvideos==0) {
                        $(thisvideogallery).find("p.error-message").text("Sorry, we couldn't find any youTube videoas for that search term. Please enter a new search term and try again.");
                        $(thisvideogallery).find("p.error-message").css({display:"block"});
                        return false;
                    }

                    numofvideos+=numofxmlvideos;
                    var numofdisplayedimages=4;
                    if (numofvideos<4) {
                        numofdisplayedimages=numofvideos;
                    }
                    var insertHTML="";
                    var displayedInsertHTML="";
                    for (var counter=0; counter<numofxmlvideos; counter++) {
                        // Every fourth image has a special class to clear right margin
                        if (((counter+1) % 4)==0) {
                            insertHTML+='<div class="end-image"><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("code:eq("+counter+")").text()+'" /></div>';
                        }
                        else {
                            insertHTML+='<div><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("code:eq("+counter+")").text()+'" /></div>';
                        }
                        if (counter<numofdisplayedimages) {
                            // Only the first 4 are displayed to begin with
                            displayedInsertHTML=insertHTML;
                        }
                    }
                    $(thisvideogallery).find("div.video-embed-holder span").css({display:"none"});
                    if (!isIE) {
                        $(thisvideogallery).find("div.video-embed-holder span").css({display:"block"});
                    }
                    $(thisvideogallery).find("div.carousel-holder div.carousel-displayed-images").empty().append(displayedInsertHTML);
                    $(thisvideogallery).find("div.carousel-stage").empty().append(insertHTML);
                    $(thisvideogallery).find("div.video-embed-holder").css({height: parseInt($(thisvideogallery).find("div.video-embed-holder").width()*350/425)});
                    $(thisvideogallery).find("div.video-embed-holder span").html('<div><object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'+$(xml).find("code:eq(0)").text()+'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+$(xml).find("code:eq(0)").text()+'" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></div>');
                    $(thisvideogallery).find("div.control-holder a").css({display:"block"});

                    if (isFireFox) {
                        $(thisvideogallery).find("div.video-embed-holder div").css({height: parseInt($(thisvideogallery).find("div.video-embed-holder").height())});
                    }

                    if (isIE) {
                        setTimeout(function() {
                            $(thisvideogallery).find("div.video-embed-holder span").css({display: "block"});
                        },100);
                    }

                    // Needed because size of element has changed;
                    setTimeout(function() {
                        removeWidgetAjaxLoader(thisvideogallery);
                        $(thisvideogallery).find("div.stage-inner-inner").css({opacity: 1});
                        precalculateWidgetCoords();
                    }, 1000);

                    $(thisvideogallery).find("form.create-gallery").css({display:"none"});
                    $(thisvideogallery).find("div.carousel-holder").css({display: "block"});
                    lastimagesrc=$(thisvideogallery).find("div.carousel-stage img:eq(0)").attr("name").split("#")[0];
                    var currentlyRotating=false;
                    initialisethumbnails = function(thisgallery) {
                        $(thisgallery).find("div.carousel-displayed-images img").unbind().click( function() {
                            if (currentlyRotating==true) {
                                return;
                            }
                            /* var clickedimage=this;
                            var newimagesrc=$(clickedimage).attr("name").split("#")[0];
                            if (newimagesrc==lastimagesrc) {
                                return;
                            }
                            lastimagesrc=newimagesrc; */
                            // currentlyRotating=true;
                            if (isIE) {
                                $(thisgallery).find("div.video-embed-holder span").css({display: "none"});
                            }
                            $(thisgallery).find("div.video-embed-holder span").empty();
                            $(thisgallery).find("div.video-embed-holder").css({height: parseInt($(thisgallery).find("div.video-embed-holder").width()*350/425)});

                            $(thisgallery).find("div.video-embed-holder span").html('<div><object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'+$(this).attr("name")+'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+$(this).attr("name")+'" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></div>');

                            if (isFireFox) {
                                $(thisvideogallery).find("div.video-embed-holder div").css({height: parseInt($(thisvideogallery).find("div.video-embed-holder").height())});
                            }

                            if (isIE) {
                                setTimeout(function() {
                                    $(thisgallery).find("div.video-embed-holder span").css({display: "block"});
                                },100);
                            }
                            return false;
                        });
                    }
                    initialisethumbnails(thisvideogallery);


                    $(thisvideogallery).find("div.control-holder a.right-button").click( function() {
                        var loadingnewthumbs=false;
                        if (carouselscrolling) {
                            return false;
                        }
                        carouselscrolling=true;
                        var previousleftmostthumb=leftmostthumb;
                        var displayedthumbnails=4;
                        var newleftmostthumb=leftmostthumb+displayedthumbnails;
                        if (newleftmostthumb>=(numofvideos-(displayedthumbnails*2))) {
                            loadingnewthumbs=true;
                        }
                        if (newleftmostthumb>=(numofvideos-displayedthumbnails)) {
                            newleftmostthumb=leftmostthumb;
                        }
                        if (displayedthumbnails>numofvideos) {
                            newleftmostthumb=0;
                        }
                        leftmostthumb=newleftmostthumb;
                        if (stillloadingnewimages) {
                            carouselscrolling=false;
                        }
                        else {
                            stillloadingnewimages=true;
                            var newcarouselheight=$(thisvideogallery).find("div.carousel-holder").height();
                            var newcarouselwidth=$(thisvideogallery).find("div.carousel-holder").width();
                            $(thisvideogallery).find("div.carousel-stage").css({width: newcarouselwidth, top: parseInt(-((previousleftmostthumb/4)*(newcarouselheight)))});
                            $(thisvideogallery).find("div.carousel").css({width:newcarouselwidth, height: newcarouselheight, display:"block"});
                            $(thisvideogallery).find("div.carousel-displayed-images").css({visibility: "hidden"});
                            $(thisvideogallery).find("div.carousel-stage").animate({top: parseInt(-((leftmostthumb/4)*(newcarouselheight)))}, 500, function() {
                                if (loadingnewthumbs) {
                                    pagenum++;
                                    $.post("/assets/ajax/getyoutubevids.php", { searchterm: searchterm, pagenum: pagenum }, function(xml) {
                                        var numofxmlvideos=$(xml).find("video").length;
                                        if ($(xml).find("thumb-src:eq(0)").text()==$(thisvideogallery).find("div.carousel-stage img:eq(0)").attr("src")) {
                                            pagenum--;
                                            stillloadingnewimages=false;
                                            return false;
                                        }
                                        var previousnumofvideos=numofvideos;
                                        numofvideos+=numofxmlvideos;
                                        var insertHTML="";
                                        for (var counter=0; counter<numofxmlvideos; counter++) {
                                            if ((((previousnumofvideos+1)+counter) % 4)==0) {
                                                insertHTML+='<div class="end-image"><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("code:eq("+counter+")").text()+'" /></div>';
                                            }
                                            else {
                                                insertHTML+='<div><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("code:eq("+counter+")").text()+'" /></div>';
                                            }
                                        }
                                        $(thisvideogallery).find("div.carousel-stage").append(insertHTML);
                                        updateCarouselDisplayImages();
                                        // initialisethumbnails(thisflickrgallery);
                                        stillloadingnewimages=false;
                                    });
                                }
                                else {
                                    stillloadingnewimages=false;
                                }
                                // Now update the display images
                                updateCarouselDisplayImages();
                                $(thisvideogallery).find("div.carousel-displayed-images").css({visibility: "visible"});
                                $(thisvideogallery).find("div.carousel").css({display:"none"});
                                carouselscrolling=false;
                            });
                        }
                        return false;
                    });

                    $(thisvideogallery).find("div.control-holder a.left-button").click( function() {
                        if (carouselscrolling) {
                            return false;
                        }
                        carouselscrolling=true;
                        var previousleftmostthumb=leftmostthumb;
                        var displayedthumbnails=4;
                        var newleftmostthumb=leftmostthumb-displayedthumbnails;
                        if (newleftmostthumb<0) {
                            newleftmostthumb=0;
                        }
                        leftmostthumb=newleftmostthumb;
                        var newcarouselheight=$(thisvideogallery).find("div.carousel-holder").height();
                        var newcarouselwidth=$(thisvideogallery).find("div.carousel-holder").width();
                        $(thisvideogallery).find("div.carousel-stage").css({width: newcarouselwidth, top: parseInt(-((previousleftmostthumb/4)*(newcarouselheight)))});
                        $(thisvideogallery).find("div.carousel").css({width:newcarouselwidth, height: newcarouselheight, display:"block"});
                        $(thisvideogallery).find("div.carousel-displayed-images").css({visibility: "hidden"});
                        $(thisvideogallery).find("div.carousel-stage").animate({top: parseInt(-((leftmostthumb/4)*(newcarouselheight)))}, 500, function() {
                            // Now update the display images
                            updateCarouselDisplayImages();
                            $(thisvideogallery).find("div.carousel-displayed-images").css({visibility: "visible"});
                            $(thisvideogallery).find("div.carousel").css({display:"none"});
                            carouselscrolling=false;
                        });
                        return false;
                    });

                });
            }
            else {
                // error message;
            }
        return false;
        });
        $(parentWidget).find("div.options-holder form.create-gallery").bind("submit", loadnewgallery);
        $(parentWidget).find("div.options-holder form.create-gallery").submit(function() {
            $(parentWidget).find("a.options-close-button").click();
        });
        // Load initial video gallery
        $(parentWidget).find("div.options-holder form.create-gallery input").val("michael_douglas_default");
        $(parentWidget).find("div.options-holder form.create-gallery").submit();
    });



    /* BOUND FUNCTION: initialiseCompetitionWidget() by Alex Kearns
     *
     * This funciton is bound to all competition widgets. It automatically sets up all the competition specific,
     * controls, ajax calls, etc for a particular competition element. New competition widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.competition-widget-holder").each( initialiseCompetitionWidget = function() {
        var parentWidget=$(this).parent();
        var competitionuserid=userId;
        var swfupload="";
        var thiscompwidget=this;
        var entryArray="";
        var initialisethumbnails="";
        var loadingnewthumbnail=false;
        var currentlyuploading=false;
        var currentcompetition="";
        var uniquetimestamp=((new Date())-0)+"imagegallery"+userId;

        var competitionWidgetId=getUniqueCompetitionId();

        var thisiframeid="iframe_file_"+getUniqueFileUploadId();

		var uploadInsertHTML='<form class="create-gallery" method="post" enctype="multipart/form-data" action="/cgi-bin/upload.cgi" method="post" target="'+thisiframeid+'">';
        uploadInsertHTML+='<input class="file-to-upload" type="file" name="file_1" />';
        uploadInsertHTML+='<div class="file-upload-progress">';
        uploadInsertHTML+='<div><span class="widget-background-colour"></span></div><p class="status">Status: Awaiting image.</p></div>';
        uploadInsertHTML+='<div class="uploaded-thumb-holder"><p></p></div>';
        uploadInsertHTML+='</form>';
        uploadInsertHTML+='<iframe class="image-upload-iframe" name="'+thisiframeid+'"></iframe>';


        $(parentWidget).find("li.file-upload-holder").append(uploadInsertHTML);

        // Terms and conditions bumf
        $(parentWidget).find("li.terms-and-conditions input").click( function() {
            $(this).parent().removeClass("tc-error");
        });

        $(parentWidget).find("li.terms-and-conditions a").click( function() {
            window.open($(this).attr("href"));
            return false;
        });

        $(parentWidget).find("input.file-to-upload").mousedown( function() {
            if (!$(parentWidget).find("li.terms-and-conditions input").attr("checked")) {
                $(parentWidget).find("li.terms-and-conditions").addClass("tc-error");
                return false;
            }
        });

        $(parentWidget).find("input.file-to-upload").click( function() {
            if (!$(parentWidget).find("li.terms-and-conditions input").attr("checked")) {
                $(parentWidget).find("li.terms-and-conditions").addClass("tc-error");
                return false;
            }
        });

        // End of terms and conditions stuff

        $(parentWidget).find("input.file-to-upload").change( function() {
            if (!$(this).val()) {
                return false;
            }
            if (currentlyuploading) {
                return false;
            }
            if (!$(parentWidget).find("li.terms-and-conditions input").attr("checked")) {
                $(parentWidget).find("li.terms-and-conditions").addClass("tc-error");
                $(this).val("")
                return false;
            }
            currentlyuploading=true;
            uniquetimestamp=((new Date())-0)+"imagegallery"+userId;

			var formurl="/cgi-bin/upload.cgi?sid="+uniquetimestamp;

            $(parentWidget).find("form.create-gallery").attr("action", formurl);

            this.form.submit();

            var tempfilename="";
            var checkprogress=function() {
                $.post("assets/ajax/upload_fileprogress.php", {sid:uniquetimestamp}, function(data) {
                    $(parentWidget).find("div.file-upload-progress div span").css({width:(parseInt(data)+"%")});
                    $(parentWidget).find("li.file-upload-holder div.file-upload-progress p.status").css({display:"block"}).text("Image uploading: "+(parseInt(data))+"%");
                    if (parseInt(data)>=100) {
                    $(parentWidget).find("li.file-upload-holder div.file-upload-progress p.status").css({display:"block"}).text("Resizing image. Please wait.");
                        var checkcomplete = function() {
                            $.post("assets/ajax/upload_gettempname.php", {sid:uniquetimestamp}, function(data) {
                                if (data=="false") {
                                    checkcomplete();
                                }
                                else {
                                    tempfilename=data.split("%2F");
                                    tempfilename=tempfilename[tempfilename.length-1];
                                    tempfilename=tempfilename.split("&")[0];

                                    $.post("assets/ajax/competition-new-entry.php", { username:userName, imagename: uniquetimestamp+".jpg", userid: userId, currentcompetition: currentcompetition, tempfilename:tempfilename, sid:uniquetimestamp }, function(data) {
                                        $(parentWidget).find("li.file-upload-holder div.file-upload-progress p.status").css({display:"block"}).text("Status: Awaiting image.");
                                        currentlyuploading=false;
                                        var compid=data;
                                        $.post("/assets/ajax/competition-get-entry.php", { entryid:compid }, function(xml) {
                                            var firstcompentry=$(xml).find("entry:eq(0)");
                                            $(thiscompwidget).find("div.home-panel img.competition-picture-home").attr("src",$(firstcompentry).find("thumbnail-src").text());
                                            $(thiscompwidget).find("div.view-panel img.competition-picture-view").attr("src",$(firstcompentry).find("image-src").text()).attr("name",$(firstcompentry).find("entry-id").text());

                                            $(thiscompwidget).find("div.view-panel p.num-of-votes").text("Based on "+$(firstcompentry).find("num-votes").text()+" votes")
                                            // Now sort out rating
                                            var firstrating=Math.round(parseFloat($(firstcompentry).find("rating").text()));
                                            $(thiscompwidget).find("ul.star-rating a").removeClass("selected").attr("name","");
                                            for (var counter=0; counter<firstrating; counter++) {
                                                $(thiscompwidget).find("ul.star-rating a:eq("+counter+")").addClass("selected").attr("name","selected");
                                            }
                                            $(thiscompwidget).find("div.home-panel div.control-holder a.view-entries").click();
                                        });
                                    });
                                }
                            });
                        }
                        checkcomplete();
                    }
                    else {
                        setTimeout( function() {
                            checkprogress();
                        },500);
                    }
                });
            }
            checkprogress();
        });

            // This function is called when the uploaded image has been
            // added to the database. The insert_id is stored in the title
            // tage of this element by the swfhandler.js routines
            /* $(thiscompwidget).find("div.swfuploader span.click-faker").click( function() {
                var compid=$(this).attr("title");
                $.post("/assets/ajax/competition-get-entry.php", { entryid:compid }, function(xml) {
                    var firstcompentry=$(xml).find("entry:eq(0)");
                    $(thiscompwidget).find("div.home-panel img").attr("src",$(firstcompentry).find("thumbnail-src").text());
                    $(thiscompwidget).find("div.view-panel img.competition-picture-view").attr("src",$(firstcompentry).find("image-src").text()).attr("name",$(firstcompentry).find("entry-id").text());

                    $(thiscompwidget).find("div.view-panel p.num-of-votes").text("Based on "+$(firstcompentry).find("num-votes").text()+" votes")
                    // Now sort out rating
                    var firstrating=Math.round(parseFloat($(firstcompentry).find("rating").text()));
                    $(thiscompwidget).find("ul.star-rating a").removeClass("selected").attr("name","");
                    for (var counter=0; counter<firstrating; counter++) {
                        $(thiscompwidget).find("ul.star-rating a:eq("+counter+")").addClass("selected").attr("name","selected");
                    }
                    $(thiscompwidget).find("div.home-panel div.control-holder a.view-entries").click();
                    initialiseSWFUploader();
                });
            });
        } */


        // Load first three competition entries

        $.post("/assets/ajax/competition-get-entries.php", { numentries:3 }, function(xml) {
            var firstcompentry=$(xml).find("entry:eq(0)");
            var secondcompentry=$(xml).find("entry:eq(1)");
            var thirdcompentry=$(xml).find("entry:eq(2)");
            $(thiscompwidget).find("div.home-panel img.competition-picture-home").attr("src",$(firstcompentry).find("thumbnail-src").text());

            $(thiscompwidget).find("div.home-panel img.competition-picture-home").css("background","#ffffff");
            $(thiscompwidget).find("div.home-panel img.competition-picture-home").css("opacity","1");
            // $(thiscompwidget).find("div.home-panel img.competition-picture-home").css("display","block");
            $(thiscompwidget).find("div.home-panel img.competition-picture-home").css("visibility","visible");

            $(thiscompwidget).find("div.view-panel img.competition-picture-view").attr("src",$(firstcompentry).find("image-src").text()).attr("name",$(firstcompentry).find("entry-id").text());
            $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(0)").attr("src",$(secondcompentry).find("thumbnail-src").text());
            $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(0)").attr("name",$(secondcompentry).find("image-src").text()+"#"+$(secondcompentry).find("creator").text()+"#"+$(secondcompentry).find("rating").text()+"#"+$(secondcompentry).find("num-votes").text()+"#"+$(secondcompentry).find("entry-id").text());
            $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(1)").attr("src",$(thirdcompentry).find("thumbnail-src").text());
            $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(1)").attr("name",$(thirdcompentry).find("image-src").text()+"#"+$(thirdcompentry).find("creator").text()+"#"+$(thirdcompentry).find("rating").text()+"#"+$(thirdcompentry).find("num-votes").text()+"#"+$(thirdcompentry).find("entry-id").text());

            $(thiscompwidget).find("div.view-panel p.num-of-votes").text("Based on "+$(firstcompentry).find("num-votes").text()+" votes")
            // Now sort out rating
            var firstrating=Math.round(parseFloat($(firstcompentry).find("rating").text()));
            $(thiscompwidget).find("ul.star-rating a").removeClass("selected").attr("name","");
            for (var counter=0; counter<firstrating; counter++) {
                $(thiscompwidget).find("ul.star-rating a:eq("+counter+")").addClass("selected").attr("name","selected");
            }
        });

        $(thiscompwidget).find("div.home-panel img").click( function() {
            $(thiscompwidget).find("div.panel").css({display: "none"});
            $(thiscompwidget).find("div.view-panel").css({display: "block"});

            setTimeout(function() {
                precalculateWidgetCoords();
            }, 100);

            return false;
        });

        $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view").click( initialisethumbnails=function() {
            if (loadingnewthumbnail) {
                return;
            }
            $(thiscompwidget).find("div.stage-inner-inner").css({opacity: 0.25});
            insertWidgetAjaxLoader(thiscompwidget);

            loadingnewthumbnail=true;
            var thisimagesrc=$(this).attr("name").split("#")[0];
            var thisusername=$(this).attr("name").split("#")[1];
            var thisrating=Math.round(parseFloat($(this).attr("name").split("#")[2]));
            var thisnumvotes=$(this).attr("name").split("#")[3];
            var thisid=$(this).attr("name").split("#")[4];

            $(thiscompwidget).find("div.view-panel img.competition-picture-view").attr("src",thisimagesrc).attr("name",thisid);
            // Now sort out the new rating
            $(thiscompwidget).find("ul.star-rating a").removeClass("selected").attr("name","");
            for (var counter=0; counter<thisrating; counter++) {
                $(thiscompwidget).find("ul.star-rating a:eq("+counter+")").addClass("selected").attr("name","selected");
            }
            $(thiscompwidget).find("div.view-panel p.num-of-votes").text("Based on "+thisnumvotes+" votes")

            if (this.className.indexOf("first")!= -1) {
                // This was the top thumbnail, so need to load it with the second
                // thumbs' details and image
                $(this).attr("src", $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(1)").attr("src"));
                $(this).attr("name", $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(1)").attr("name"));
            }

            setTimeout(function() {
                precalculateWidgetCoords();
            }, 100);
            // Now hide the second thumbnail
            var newthumbnail=$('<img class="competition-sub-picture-view widget-border-colour-light" />');
            $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(1)").remove();
            // And now load a random new thumbnail
            $.post("/assets/ajax/competition-get-entries.php", { numentries:1 }, function(xml) {
                var newthumbentry=$(xml).find("entry:eq(0)");
                $(newthumbnail).attr("src",$(newthumbentry).find("thumbnail-src").text());
                $(newthumbnail).attr("name",$(newthumbentry).find("image-src").text()+"#"+$(newthumbentry).find("creator").text()+"#"+$(newthumbentry).find("rating").text()+"#"+$(newthumbentry).find("num-votes").text()+"#"+$(newthumbentry).find("entry-id").text());
                $(newthumbnail).bind("click", initialisethumbnails);
                $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(0)").after($(newthumbnail));
                loadingnewthumbnail=false;
                removeWidgetAjaxLoader(thiscompwidget);
                $(thiscompwidget).find("div.stage-inner-inner").css({opacity: 1});
            });
        return false;
        });

        // Rating system
        $(thiscompwidget).find("ul.star-rating a").hover( function() {
            $(thiscompwidget).find("ul.star-rating a").removeClass("selected");
            var position=parseInt($(this).text());
            for (var counter=0; counter<position; counter++) {
                $(thiscompwidget).find("ul.star-rating a:eq("+counter+")").addClass("selected");
            }
        }, function() {
            $(thiscompwidget).find("ul.star-rating a").removeClass("selected");
            $(thiscompwidget).find("ul.star-rating a").each( function() {
                if ($(this).attr("name")=="selected") {
                    $(this).addClass("selected");
                }
            });
        });

        // Clicked on a star so update rating in database and
        // load new competition entry by faking a click on a thumbnail
        $(thiscompwidget).find("ul.star-rating a").click( function() {
            var rating=$(this).text();
            var entryid=+$(thiscompwidget).find("div.view-panel img.competition-picture-view").attr("name");
            $.post("/assets/ajax/competition-update-rating.php", { rating:rating, entryid:entryid });
            $(thiscompwidget).find("div.view-panel img.competition-sub-picture-view:eq(0)").click();
            return false;

        });
        $(thiscompwidget).find("select.star-rating").click( function() {
            if ($(this).val() && parseInt($(this).val()) > 0) {
                $(thiscompwidget).find("ul.star-rating a:eq("+(parseInt($(this).val())-1)+")").click();
                $(thiscompwidget).find("select.star-rating").get()[0].selectedIndex=0;
            }
        });

        // Hide all panels but the home panel to start
        $(this).find("div.panel").css({display: "none"});
        $(this).find("div.home-panel").css({display: "block"});


        $(this).find("div.panel div.control-holder a").click( function() {
            // The class of the next panel to be displayed is stored
            // in the name attribute of the a tag that is clicked
            var nextpanel=$(this).attr("name");
            if (nextpanel=="submit-panel" && userId=="") {

                insertLoginErrorMessage(thiscompwidget,"You need to be signed up and logged in to enter this competition. Click one of the options below to sign up or login.");

                // loginPopup("signup-panel");
                return false;
            }
            $(thiscompwidget).find("div.panel").css({display: "none"});
            $(thiscompwidget).find("div."+nextpanel).css({display: "block"});
            setTimeout(function() {
                precalculateWidgetCoords();
            }, 100);
            return false;
        });


    });
    
    

	/* BOUND FUNCTION: initialiseNmeiPod() by Nick Dunn
	*
	* Sets up the NME competition widget
	*********************************************************************************/

	$("div#drag-column-holder div.widget div.nmeipod-widget-holder").each( initialiseNmeiPod = function() {
		var thisWidget=$(this).parents("div.widget");
		var thisContent=this;
		
		$(thisWidget).find("div.nmeipod-map-inner a.enter-now").click(function() {
			$(thisWidget).find("div.nmeipod-map").removeClass("nmeipod-map").addClass("nmeipod-form");
			return false;
		});
		
		$(thisWidget).find("label[@for='nme-tc'] a").click(function() {
			$("body").css({overflow:"hidden"});
			var pageheight=getViewportDimensions()[1];
			if (pageheight < $("body").height()) {
				pageheight=$("body").height();
			}
			$("div#login-popup-fader").css({height:pageheight, width:$("body").width()});
			$("div#login-popup-fader").css({display:"block"});
			
			$("div#nmeipod-terms-holder").css({height:pageheight, width:$("body").width()});
			$(thisWidget).find("select").css("visibility", "hidden");
			$("div.theme-background-foreground").append("<div id=\"nmeipod-terms-holder\"></div>");
			$("div#nmeipod-terms-holder")
			.append("<div class=\"nmeipod-terms\">" + $(thisWidget).find("div.nmeipod-terms").html() + "</div>")
			.css("display", "block")
			.find("a.close").click(function() {
				$(thisWidget).find("select").css("visibility", "visible");
				$("div#login-popup-fader").css("display", "none");
				$("div#nmeipod-terms-holder").remove();
				$("body").css({overflow:"visible"});
			});
			
			// object detection to correctly get position scrolled (Y offset)
			if (window.innerHeight)
			{
				  pos = window.pageYOffset
			}
			else if (document.documentElement && document.documentElement.scrollTop)
			{
				pos = document.documentElement.scrollTop
			}
			else if (document.body)
			{
				  pos = document.body.scrollTop
			}
								
			$("#nmeipod-terms-holder div.nmeipod-terms").css("margin-top", (pos + 110) + "px")	
			
			return false;
		});
		
		
        
        
		
		$(thisWidget).find("div.nmeipod-form-inner form").submit(function() {
			var isValid = true;
			
			if ($(thisWidget).find("input[@name='nme-tc']:checked").val() == null) {
				isValid = false;
				$(thisWidget).find("label[@for='nme-tc']").addClass("nme-error");
			} else {
				$(thisWidget).find("label[@for='nme-tc']").removeClass("nme-error");
			}
			
			if ($(thisWidget).find("input[@name='nme-name']").val() == "") {
				isValid = false;
				$(thisWidget).find("input[@name='nme-name']").addClass("nme-error");
			} else {
				$(thisWidget).find("input[@name='nme-name']").removeClass("nme-error");
			}
			
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;			
			if (reg.test($(thisWidget).find("input[@name='nme-email']").val()) == false) {
				isValid = false;
				$(thisWidget).find("input[@name='nme-email']").addClass("nme-error");
			} else {
				$(thisWidget).find("input[@name='nme-email']").removeClass("nme-error");
			}
			
			if ($(thisWidget).find("input[@name='nme-tel']").val() == "") {
				isValid = false;
				$(thisWidget).find("input[@name='nme-tel']").addClass("nme-error");
			} else {
				$(thisWidget).find("input[@name='nme-tel']").removeClass("nme-error");
			}
			
			if (isValid) {
				$(thisWidget).find("label[@for='nme-tc']").removeClass("nme-error");
				$.post("/assets/ajax/nmeipod-new-entry.php", {
					name: $(thisWidget).find("input[@name='nme-name']").val(),
					email: $(thisWidget).find("input[@name='nme-email']").val(),
					tel: $(thisWidget).find("input[@name='nme-tel']").val(),
					venue: $(thisWidget).find("select[@name='nme-venue'] option:selected").text(),
					optin: $(thisWidget).find("input[@name='nme-optin']:checked").val()
				}, function(data) {
					$(thisWidget).find("div.nmeipod-form").removeClass("nmeipod-form").addClass("nmeipod-thanks");
				});
			}		
			
			return false;
		});
		
		$(thisWidget).find("div.nmeipod-thanks-inner a.back").click(function() {
			$(thisWidget).find("div.nmeipod-thanks").removeClass("nmeipod-thanks").addClass("nmeipod-map");
		})
	});




    
    /* BOUND FUNCTION: initialiseNmeCompetition() by Nick Dunn
	*
	* Sets up the NME competition widget
	*********************************************************************************/

	$("div#drag-column-holder div.widget div.nmecompetition-widget-holder").each( initialiseNmeCompetition = function() {
		var thisWidget=$(this).parents("div.widget");
		var thisContent=this;
		
		$(thisWidget).find("div.nmecompetition-map-inner a.enter-now").click(function() {
			$(thisWidget).find("div.nmecompetition-map").removeClass("nmecompetition-map").addClass("nmecompetition-form");
			return false;
		});
		
		$(thisWidget).find("label[@for='nme-tc'] a").click(function() {
			$("body").css({overflow:"hidden"});
			var pageheight=getViewportDimensions()[1];
			if (pageheight < $("body").height()) {
				pageheight=$("body").height();
			}
			$("div#login-popup-fader").css({height:pageheight, width:$("body").width()});
			$("div#login-popup-fader").css({display:"block"});
			
			$("div#nmecompetition-terms-holder").css({height:pageheight, width:$("body").width()});
			$(thisWidget).find("select").css("visibility", "hidden");
			$("div.theme-background-foreground").append("<div id=\"nmecompetition-terms-holder\"></div>");
			$("div#nmecompetition-terms-holder")
			.append("<div class=\"nmecompetition-terms\">" + $(thisWidget).find("div.nmecompetition-terms").html() + "</div>")
			.css("display", "block")
			.find("a.close").click(function() {
				$(thisWidget).find("select").css("visibility", "visible");
				$("div#login-popup-fader").css("display", "none");
				$("div#nmecompetition-terms-holder").remove();
				$("body").css({overflow:"visible"});
			});
			
			// object detection to correctly get position scrolled (Y offset)
			if (window.innerHeight)
			{
				  pos = window.pageYOffset
			}
			else if (document.documentElement && document.documentElement.scrollTop)
			{
				pos = document.documentElement.scrollTop
			}
			else if (document.body)
			{
				  pos = document.body.scrollTop
			}
								
			$("#nmecompetition-terms-holder div.nmecompetition-terms").css("margin-top", (pos + 110) + "px")	
			
			return false;
		});
		
		
        
        
		
		$(thisWidget).find("div.nmecompetition-form-inner form").submit(function() {
			var isValid = true;
			
			if ($(thisWidget).find("input[@name='nme-tc']:checked").val() == null) {
				isValid = false;
				$(thisWidget).find("label[@for='nme-tc']").addClass("nme-error");
			} else {
				$(thisWidget).find("label[@for='nme-tc']").removeClass("nme-error");
			}
			
			if ($(thisWidget).find("input[@name='nme-name']").val() == "") {
				isValid = false;
				$(thisWidget).find("input[@name='nme-name']").addClass("nme-error");
			} else {
				$(thisWidget).find("input[@name='nme-name']").removeClass("nme-error");
			}
			
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;			
			if (reg.test($(thisWidget).find("input[@name='nme-email']").val()) == false) {
				isValid = false;
				$(thisWidget).find("input[@name='nme-email']").addClass("nme-error");
			} else {
				$(thisWidget).find("input[@name='nme-email']").removeClass("nme-error");
			}
			
			if ($(thisWidget).find("input[@name='nme-tel']").val() == "") {
				isValid = false;
				$(thisWidget).find("input[@name='nme-tel']").addClass("nme-error");
			} else {
				$(thisWidget).find("input[@name='nme-tel']").removeClass("nme-error");
			}
			
			if (isValid) {
				var ebRand = Math.random()+ ' ';
				ebRand = ebRand * 1000000;
				$("body").append('<img src="HTTP://activity.serving-sys.com/Activity/Pipe.asp?ActivityID=11561&rnd=' + ebRand + '" style=\'visibility:hidden;width:1px;height:1px;\'/>');
				$(thisWidget).find("label[@for='nme-tc']").removeClass("nme-error");
				$.post("/assets/ajax/nmecompetition-new-entry.php", {
					name: $(thisWidget).find("input[@name='nme-name']").val(),
					email: $(thisWidget).find("input[@name='nme-email']").val(),
					tel: $(thisWidget).find("input[@name='nme-tel']").val(),
					venue: $(thisWidget).find("select[@name='nme-venue'] option:selected").text(),
					optin: $(thisWidget).find("input[@name='nme-optin']:checked").val()
				}, function(data) {
					$(thisWidget).find("div.nmecompetition-form").removeClass("nmecompetition-form").addClass("nmecompetition-thanks");
				});
			}		
			
			return false;
		});
		
		$(thisWidget).find("div.nmecompetition-thanks-inner a.back").click(function() {
			$(thisWidget).find("div.nmecompetition-thanks").removeClass("nmecompetition-thanks").addClass("nmecompetition-map");
		})
	});



    /* HIDE COMPETITION PANELS by Alex Kearns
     *
     * This simply hides the competition widget panels that don't need displaying at the start
     ************************************************************************************************/
    $("div.competition-widget-holder").find("div.panel").css({display: "none"});
    $("div.competition-widget-holder").find("div.home-panel").css({display: "block"});



    /* BOUND FUNCTION: initialiseCalendarWidget() by Alex Kearns
     *
     * This funciton is bound to all calendar widgets. It automatically sets up all the calendar specific,
     * controls, ajax calls, etc for a particular calendar element. New calendar widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/

    $("div#drag-column-holder div.widget div.calendar-widget-holder").each( initialiseCalendarWidget = function() {
        var parentWidget=$(this).parent().parent();
        var today=new Date();
        var calendarDay=today.getDate();
        var calendarMonth=today.getMonth();
        var calendarYear=takeYear(today);
        var calendarholder=$(this).find("div.calendar-html-holder");
        var selectedDate=new Date();
        var thiscalendar=this;
        var thiswidgetid=$(parentWidget).find("span.widget-info-id").text();
        generateCalendar(calendarMonth,calendarYear,calendarholder,selectedDate);
        var initialiseCalendar=function() {
            $(calendarholder).find("a.select-previous-month").click( function() {
                calendarMonth=calendarMonth-1;
                if (calendarMonth==-1) {
                    calendarMonth=11;
                    calendarYear--;
                }
                generateCalendar(calendarMonth,calendarYear,calendarholder,selectedDate);
                initialiseCalendar();
                return false;
            });
            $(calendarholder).find("a.select-next-month").click( function() {
                calendarMonth=calendarMonth+1;
                if (calendarMonth==12) {
                    calendarMonth=0;
                    calendarYear++;
                }
                generateCalendar(calendarMonth,calendarYear,calendarholder,selectedDate);
                initialiseCalendar();
                return false;
            });
            $(calendarholder).find("td").hover( function() {
                if (drag) {
                    return;
                }
                if ($(this).find("p").text() != "") {
                    $(this).addClass("highlighted");
                }
            }, function() {
                $(this).removeClass("highlighted");
            });

            $(calendarholder).find("td").click( function() {
                if ($(this).find("p").text() != "") {
                    $(calendarholder).find("td").removeClass("selected");
                    $(this).addClass("selected");
                    var datetext=$(this).find("span.date-week-day").text()+", <span>";
                    datetext+=$(this).find("span.date-day").text();
                    datetext+=$(this).find("span.date-day-suffix").text()+" ";
                    datetext+=$(this).find("span.date-month-text").text()+" ";
                    datetext+=$(this).find("span.date-year").text()+"</span>";
                    $(calendarholder).find("h6").html(datetext);
                    $(thiscalendar).find("div.gig-details-holder").empty();
                    var thistd=this;
                    var selectedlocation=$(thiscalendar).find("select.gig-area-select").val();
                    var thismonth  = $(thistd).find("span.date-month").text()
                    thismonth  = parseInt(thismonth) + 1
                    $.post("/assets/ajax/getnmegigs.php", { location: selectedlocation, day: $(thistd).find("span.date-day").text(), month: thismonth, year: $(thistd).find("span.date-year").text() }, function(xml) {
                        var numofgigs=$(xml).find("gig").length;
                        if (numofgigs) {
                            var insertHTML="<ul>\n";
                            var highlightflag=1;
                            for (var counter=0; counter<numofgigs; counter++) {
                                var highlightext="";
                                if (highlightflag=1-highlightflag) {
                                    highlightext=' class="highlight" ';
                                }
                                insertHTML+="<li"+highlightext+">\n";
                                insertHTML+="<h5 class='widget-colour'>"+$(xml).find("gig:eq("+counter+")").find("name").text()+"</h5>\n";
                                insertHTML+="<p>"+$(xml).find("gig:eq("+counter+")").find("venue").text()+"</p>\n";
                                if ($(xml).find("gig:eq("+counter+")").find("ticket-link").text()) {
                                    insertHTML+='<a href="'+$(xml).find("gig:eq("+counter+")").find("ticket-link").text()+'">GET TICKETS</a>\n';
                                }
                                insertHTML+="</li>\n";
                            }
                            insertHTML+="</ul>\n";
                            $(thiscalendar).find("div.gig-details-holder").empty().append(insertHTML);
                            $(thiscalendar).find("div.gig-details-holder a").click(function() {
                                window.open($(this).attr("href"));
                                return false;
                            });
                        }
                        else {
                            $(thiscalendar).find("div.gig-details-holder").empty().append("<ul><li><h5 class='widget-colour'>Sorry, we could not find any gigs in "+selectedlocation+" on this day</h5></li></ul>");
                        }
                    });
                }
            });

            $(thiscalendar).find("select.gig-area-select").change( function() {
                $(parentWidget).find("span.widget-info-setting").text($(this).val());
                $(calendarholder).find("td.selected").click();

                thiswidgetid=$(parentWidget).find("span.widget-info-id").text();
                if (thiswidgetid) {
                    $.post("assets/ajax/state-update-settings.php", { newsetting: $(this).val(), widgetid: thiswidgetid}, function(data) {
                            // Maybe display error message if necessary
                    });
                }

            });

        }
        initialiseCalendar();
        var storedmonth=$(parentWidget).find("span.widget-info-setting").text();
        if (storedmonth) {
            $(thiscalendar).find("select.gig-area-select").val(storedmonth);
        }
        $(thiscalendar).find("div.calendar-html-holder td.selected").click();
    });


    /* BOUND FUNCTION: initialiseFlickrGallery() by Alex Kearns
     *
     * This funciton is bound to all flickr gallery widgets. It automatically sets up all the flickr specific,
     * controls, ajax calls, etc for a particular widget. New flickr gallery widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.flickr-gallery-holder").each( initialiseFlickrGallery = function() {
        var parentWidget=$(this).parent();
        var thisflickrgallery=this;
        var loadnewgallery="";
        var previousflickrusername=$(parentWidget).parent().find("span.widget-info-setting").text();;
        var flickrWidgetId=getUniqueFlickrId();
        var gallerytype="";
        var flickrusername=$(parentWidget).parent().find("span.widget-info-setting").text();
        var lastimagesrc="";
        var pagenum=1;
        var numofimages=0;
        var currentlyuploading=false;
        var uniquetimestamp=((new Date())-0);
        var thiswidgetid=$(parentWidget).parent().find("span.widget-info-id").text();

        var thisiframeid="iframe_file_"+getUniqueFileUploadId();


		var uploadInsertHTML='<form class="create-gallery" method="post" enctype="multipart/form-data" action="/cgi-bin/upload.cgi" method="post" target="'+thisiframeid+'">';
        uploadInsertHTML+='<h4>Choose gallery type</h4>';
        uploadInsertHTML+='<p>Either create a gallery from your Flickr account or upload images (jpg format only) one by one to create your gallery.</p>';
        uploadInsertHTML+='<label>Flickr Gallery</label>';
        uploadInsertHTML+='<input class="gallery-type flickr-gallery-type" name="gallery-type" checked="checked" type="radio" />';
        uploadInsertHTML+='<label>Upload images</label>';
        uploadInsertHTML+='<input class="gallery-type upload-gallery-type" name="gallery-type" type="radio" />';
        uploadInsertHTML+='<div class="options-divider"></div>';
        uploadInsertHTML+='<span class="flickr-selection">';
        uploadInsertHTML+='<label class="light" for="username">Flickr username: </label>';
        uploadInsertHTML+='<input class="flickr-name" type="text" name="flickr-name" />';
        uploadInsertHTML+='</span>';
        uploadInsertHTML+='<span class="upload-selection">';
        uploadInsertHTML+='<input class="file-to-upload" type="file" name="file_1" />';
        uploadInsertHTML+='<div class="file-upload-progress">';
        uploadInsertHTML+='<div><span class="widget-background-colour"></span></div><p class="status">Status: Awaiting image.</p></div>';
        uploadInsertHTML+='<div class="uploaded-thumb-holder"><p></p></div>';
        uploadInsertHTML+="<p>Finished uploading your images. Click 'Update your gallery' to add the new images to your gallery.</p>";
        uploadInsertHTML+='</span>';
        uploadInsertHTML+='<input class="load-gallery-button" type="submit" value="Create Flickr gallery" />';
        uploadInsertHTML+='<p class="error-message"></p>';
        uploadInsertHTML+='</form>';
        uploadInsertHTML+='<iframe class="image-upload-iframe" name="'+thisiframeid+'"></iframe>';

        $(parentWidget).find("ul.widget-flickr-options li.gallery-settings").prepend(uploadInsertHTML);

        $(parentWidget).find("input.file-to-upload").change( function() {
            if (currentlyuploading) {
                return false;
            }
            currentlyuploading=true;
            uniquetimestamp=((new Date())-0)+"imagegallery"+userId;

			var formurl="/cgi-bin/upload.cgi?sid="+uniquetimestamp;

            $(parentWidget).find("form.create-gallery").attr("action", formurl);

            this.form.submit();

            var tempfilename="";
            var checkprogress=function() {
                $.post("assets/ajax/upload_fileprogress.php", {sid:uniquetimestamp}, function(data) {
                    $(parentWidget).find("div.file-upload-progress div span").css({width:(parseInt(data)+"%")});
                    $(parentWidget).find("div.file-upload-progress p.status").css({display:"block"}).text("Image uploading: "+(parseInt(data))+"%");
                    if (parseInt(data)>=100) {
                    $(parentWidget).find("div.file-upload-progress p.status").css({display:"block"}).text("Generating thumbnail. Please wait.");
                        var checkcomplete = function() {
                            $.post("assets/ajax/upload_gettempname.php", {sid:uniquetimestamp}, function(data) {
                                if (data=="false") {
                                    checkcomplete();
                                }
                                else {
                                    tempfilename=data.split("%2F");
                                    tempfilename=tempfilename[tempfilename.length-1];
                                    tempfilename=tempfilename.split("&")[0];

                                    $.post("/assets/ajax/image-gallery-new-image.php", { imagename: uniquetimestamp+".jpg", userid: userId, tempfilename: tempfilename, sid:uniquetimestamp }, function(data) {
                                        var insertid=data.split("#")[0];
                                        var imagefilename=data.split("#")[1];
                                        $(parentWidget).find("div.uploaded-thumb-holder").append('<img src="'+imagefilename+'" alt="'+insertid+'" />');
                                        $(parentWidget).find("div.uploaded-thumb-holder p").css({display:"block"}).text("Recently uploaded images.");
                                        var newheight = specialFindHeight($(parentWidget).find("div.options-holder div.options-holder-inner"),$(parentWidget).width()-26);
                                        $(parentWidget).find("div.options-holder").css({height: newheight+40});
                                        $(parentWidget).find("div.options-holder input.load-gallery-button").val("Update your gallery").css({marginLeft:0});
                                        $(parentWidget).find("div.file-upload-progress p.status").css({display:"block"}).text("Status: Awaiting image.");
                                        currentlyuploading=false;
                                    });
                                }
                            });
                        }
                        checkcomplete();
                    }
                    else {
                        setTimeout( function() {
                            checkprogress();
                        },500);
                    }
                });
            }
            checkprogress();
        });



        // Toggle which options are displayed when user clicks on either
        // Flickr gallery or upload image gallery radio button
        $(parentWidget).find("div.options-holder input.gallery-type").click(function() {
            if (this.className.indexOf("flickr") != -1) {
                $(parentWidget).find("div.options-holder span.flickr-selection").css({display: "block"});
                $(parentWidget).find("div.options-holder span.upload-selection").css({display: "none"});
                $(parentWidget).find("div.options-holder input.load-gallery-button").val("Create Flickr gallery").css({marginLeft: "90px"});
                var newheight = specialFindHeight($(parentWidget).find("div.options-holder div.options-holder-inner"),$(parentWidget).width()-26);
                $(parentWidget).find("div.options-holder").css({height: newheight+40});
            }
            else {
                if (userId=="") {
                    $(parentWidget).find("div.options-holder input.gallery-type").each( function() {
                        if (this.className.indexOf("flickr") != -1) {
                            $(this).attr("checked", "checked");
                        }
                        else {
                            $(this).attr("checked", "");
                        }
                    });
                    loginPopup("signup-panel");
                    return false;
                }

                $(parentWidget).find("div.options-holder span.flickr-selection").css({display: "none"});
                $(parentWidget).find("div.options-holder span.upload-selection").css({display: "block"});
                $(parentWidget).find("div.options-holder input.load-gallery-button").val("Load your gallery").css({marginLeft: 0});
                var newheight = specialFindHeight($(parentWidget).find("div.options-holder div.options-holder-inner"),$(parentWidget).width()-26);
                $(parentWidget).find("div.options-holder").css({height: newheight+40});
            }
        });


        // Open the correct options block when user clicks on create gallery link
        var initialiseopengalleryoption = function() {
            $(thisflickrgallery).find("div.create-gallery-holder a.create-gallery").click( function() {
                $(parentWidget).find("div.options-holder li").css({display:"none"});
                $(parentWidget).find("div.options-holder li:eq(0)").css({display:"block"});
                var newheight = specialFindHeight($(parentWidget).find("div.options-holder div.options-holder-inner"),$(parentWidget).width()-26);
                $(parentWidget).find("div.options-holder").css({display: "block"}).animate({height: newheight+40},500, function() {});
                return false;
            });
        }

        initialiseopengalleryoption();

        // Close the options block when the form is submitted
        $(parentWidget).find("div.options-holder form.create-gallery").submit(function() {
            $(parentWidget).find("a.options-close-button").click();
        });


        $(this).find("div.options-holder form.create-gallery").submit( loadnewgallery=function() {

            var lastcontainerheight=150;
            var leftmostthumb=0;
            var thumbnailwidth=50;
            var carouselscrolling=false;
            var alreadyloaded="";
            var stillloadingnewimages=false;

            var updateCarouselDisplayImages = function() {
                for (var counter=0; counter<8; counter++) {
                    var selecteddisplayimage=$(thisflickrgallery).find("div.carousel-displayed-images img:eq("+counter+")");
                    var selectedcarouselimage=$(thisflickrgallery).find("div.carousel-stage img:eq("+(counter+leftmostthumb)+")");
                    if (selectedcarouselimage.length) {
                        $(selecteddisplayimage).css({display:"block"})
                        $(selecteddisplayimage).attr("src", $(selectedcarouselimage).attr("src"))
                        $(selecteddisplayimage).attr("name", $(selectedcarouselimage).attr("name"))
                    }
                    else {
                        $(selecteddisplayimage).css({display:"none"})
                    }
                }
            }

            if ($(this).find("input.flickr-name").attr("value") && $(this).find("input.load-gallery-button").val()=="Create Flickr gallery") {
                // User wants to create a Flickr gallery and has entered username
                flickrusername=$(this).find("input.flickr-name").attr("value");
                $(parentWidget).parent().find("span.widget-info-setting").text(flickrusername);
                gallerytype="flickr";
            }
            else if ($(this).find("input.load-gallery-button").val()=="Load your gallery" || $(this).find("input.load-gallery-button").val()=="Update your gallery") {
                // User wants to create an image upload gallery
                gallerytype="upload";
            }
            else {
                gallerytype="";
                // Should really display an error message here
            }

            if (gallerytype) {

                $(thisflickrgallery).find("div.stage-inner-inner").css({opacity: 0.25});
                insertWidgetAjaxLoader(thisflickrgallery);

                $.post("/assets/ajax/getuserflickrimages.php", { username: flickrusername, pagenum: pagenum, userid: userId, gallerytype: gallerytype }, function(xml) {
                    var numofxmlimages=$(xml).find("image").length;
                    if (numofxmlimages==0) {
                        flickrusername=previousflickrusername;
                        $(this).find("input.flickr-name").attr("value",flickrusername);
                        removeWidgetAjaxLoader(thisflickrgallery);
                        insertWidgetErrorMessage(thisflickrgallery,"Sorry, we couldn't find any pictures for the Flickr account you entered. Please go to the settings option in this widget's menu, and try a new search term");

                        return false;
                    }
                    thiswidgetid=$(parentWidget).parent().find("span.widget-info-id").text();
                    if ((previousflickrusername != flickrusername) && thiswidgetid) {
                        $.post("assets/ajax/state-update-settings.php", { newsetting: flickrusername, widgetid: thiswidgetid}, function(data) {
                            // Maybe display error if necessary
                        });
                    }
                    lastimagesrc="";
                    pagenum=1;
                    numofimages=0;
                    $(thisflickrgallery).find("*").unbind();
                    previousflickrusername=flickrusername;
                    numofimages+=numofxmlimages;
                    var numofdisplayedimages=8;
                    if (numofimages<8) {
                        numofdisplayedimages=numofimages;
                    }
                    var insertHTML="";
                    var displayedInsertHTML="";
                    for (var counter=0; counter<numofxmlimages; counter++) {
                        // Every fourth image has a special class to clear right margin
                        if (((counter+1) % 4)==0) {
                            insertHTML+='<div class="end-image"><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("image-src:eq("+counter+")").text()+'#'+$(xml).find("image-width:eq("+counter+")").text()+'#'+$(xml).find("image-height:eq("+counter+")").text()+'" /></div>';
                        }
                        else {
                            insertHTML+='<div><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("image-src:eq("+counter+")").text()+'#'+$(xml).find("image-width:eq("+counter+")").text()+'#'+$(xml).find("image-height:eq("+counter+")").text()+'" /></div>';
                        }
                        if (counter<numofdisplayedimages) {
                            // Only the first 8 are displayed to begin with
                            displayedInsertHTML=insertHTML;
                        }
                    }
                    $(thisflickrgallery).find("div.intro-blurb").css({display:"none"});
                    $(thisflickrgallery).find("div.create-gallery-holder a.create-gallery").css({display:"none"});

                    // Open colours tab when customise it is clicked
                    $(thisflickrgallery).find("div.create-gallery-holder a.customise-it").click( function() {
                        $(parentWidget).find("div.options-holder li").css({display:"none"});
                        $(parentWidget).find("div.options-holder li:eq(1)").css({display:"block"});
                        var newheight = specialFindHeight($(parentWidget).find("div.options-holder div.options-holder-inner"),$(parentWidget).width()-26);
                        $(parentWidget).find("div.options-holder").css({display: "block"}).animate({height: newheight+40},500, function() {});
                        return false;
                    });

                    $(thisflickrgallery).find("div.create-gallery-holder a.customise-it").css({display:"block"});
                    $(thisflickrgallery).find("div.carousel-holder div.carousel-displayed-images").empty().append(displayedInsertHTML);
                    $(thisflickrgallery).find("div.carousel-stage").empty().append(insertHTML);

                    var firstimageheight=parseInt($(thisflickrgallery).find("img.main-image").width()*parseInt($(xml).find("image-height:eq(0)").text())/parseInt($(xml).find("image-width:eq(0)").text()));
                    $(thisflickrgallery).find("img.main-image").attr("src",$(xml).find("image-src:eq(0)").text());
                    $(thisflickrgallery).find("img.main-image").css({height:firstimageheight});
                    $(thisflickrgallery).find("img.main-image").parent().css({height:firstimageheight});
                    $(thisflickrgallery).find("div.control-holder a").css({display:"block"});
                    if (isIE) {
                        var initialimage=$(thisflickrgallery).find("img.main-image");
                        var iecheckinitialimageloaded="";
                        setTimeout( iecheckinitialimageloaded=function() {
                            if ($(initialimage).get()[0].complete) {
                                lastcontainerheight=$(initialimage).height();
                                $(initialimage).parent().css({height:lastcontainerheight});
                                precalculateWidgetCoords();
                                removeWidgetAjaxLoader(thisflickrgallery);
                                $(thisflickrgallery).find("div.stage-inner-inner").css({opacity: 1});
                                }
                            else {
                                setTimeout( function() {
                                    iecheckinitialimageloaded();
                                },50);
                            }
                        });
                    }
                    else {
                        $(thisflickrgallery).find("img.main-image").load(function() {
                            lastcontainerheight=$(this).height();
                            $(this).parent().css({height:lastcontainerheight});
                            precalculateWidgetCoords();
                            removeWidgetAjaxLoader(thisflickrgallery);
                            $(thisflickrgallery).find("div.stage-inner-inner").css({opacity: 1});
                        });
                    }
                    $(thisflickrgallery).find("form").css({display:"none"});
                    $(thisflickrgallery).find("div.main-image-holder").css({display: "block"});
                    $(thisflickrgallery).find("div.carousel-holder").css({display: "block"});
                    lastimagesrc=$(thisflickrgallery).find("div.carousel-stage img:eq(0)").attr("name").split("#")[0];
                    var currentlyRotating=false;
                    initialisethumbnails = function(thisgallery) {
                        $(thisgallery).find("div.carousel-displayed-images img").unbind().click( function() {
                            if (currentlyRotating==true) {
                                return;
                            }
                            var clickedimage=this;
                            var newimagesrc=$(clickedimage).attr("name").split("#")[0];
                            if (newimagesrc==lastimagesrc) {
                                return;
                            }
                            lastimagesrc=newimagesrc;
                            currentlyRotating=true;
                            $(thisgallery).find("img.main-image").animate({opacity:0}, 500, function() {
                                var newcontainerheight=($(this).width()/parseInt($(clickedimage).attr("name").split("#")[1])*parseInt($(clickedimage).attr("name").split("#")[2]));
                                var flickranimationtime=Math.sqrt(Math.pow(((newcontainerheight-lastcontainerheight)),2))*4+1;
                                if (lastcontainerheight==newcontainerheight) { // new image is same size
                                    var newimage=$('<img class="main-image" alt="" />');
                                    $(newimage).css({visibility: "hidden", opacity: 0, height: newcontainerheight});
                                    $(this).parent().empty().append(newimage);
                                    $(newimage).attr("src", $(clickedimage).attr("name").split("#")[0]);
                                    if(isIE) {
                                        var iecheckimageloaded="";
                                        setTimeout( iecheckimageloaded=function() {
                                            if ($(newimage).get()[0].complete) {
                                                $(newimage).css({visibility: "visible"});
                                                $(newimage).animate({opacity:1},500, function() {
                                                    currentlyRotating=false;
                                                    precalculateWidgetCoords();
                                                    return false;
                                                });
                                            }
                                            else {
                                                setTimeout( function() {
                                                    iecheckimageloaded();
                                                },50);
                                            }
                                        },50);
                                    }
                                    else { // Not ie
                                        $(newimage).unbind().load( function() {
                                            $(newimage).css({visibility: "visible"});
                                            $(newimage).animate({opacity:1},500, function() {
                                                currentlyRotating=false;
                                                precalculateWidgetCoords();
                                                return false;
                                            });
                                        });
                                    }
                                }
                                else { // New image is not the same size
                                    lastcontainerheight=newcontainerheight;
                                    var newimage=$('<img class="main-image" alt="" />');
                                    $(newimage).css({visibility: "hidden", opacity: 0, height: newcontainerheight});
                                    $(this).parent().empty().append(newimage);
                                    $(thisgallery).find("div.main-image-holder").animate({height: parseInt(newcontainerheight)},flickranimationtime,function(){
                                        $(newimage).attr("src", $(clickedimage).attr("name").split("#")[0]);
                                        if(isIE) {
                                            var iecheckimageloaded="";
                                            setTimeout( iecheckimageloaded=function() {
                                                if ($(newimage).get()[0].complete) {
                                                    $(newimage).css({visibility: "visible"});
                                                    $(newimage).animate({opacity:1},500, function() {
                                                        currentlyRotating=false;
                                                        return false;
                                                    });
                                                }
                                                else {
                                                    setTimeout( function() {
                                                        iecheckimageloaded();
                                                    },50);
                                                }
                                            },50);
                                        }
                                        else {
                                            $(newimage).unbind().load( function() {
                                                $(newimage).css({visibility: "visible"});
                                                $(newimage).animate({opacity:1},500, function() {
                                                    currentlyRotating=false;
                                                    return false;
                                                });
                                            });
                                        }

                                    });
                                }
                            });
                        return false;
                        });
                    }
                    initialisethumbnails(thisflickrgallery);
                    $(thisflickrgallery).find("div.control-holder a.right-button").click( function() {
                        var loadingnewthumbs=false;
                        if (carouselscrolling) {
                            return false;
                        }
                        carouselscrolling=true;
                        var previousleftmostthumb=leftmostthumb;
                        var displayedthumbnails=4;
                        var newleftmostthumb=leftmostthumb+displayedthumbnails;
                        if (newleftmostthumb>=(numofimages-(displayedthumbnails*2))) {
                            loadingnewthumbs=true;
                        }
                        if (newleftmostthumb>=(numofimages-displayedthumbnails)) {
                            newleftmostthumb=leftmostthumb;
                        }
                        if (displayedthumbnails>numofimages) {
                            newleftmostthumb=0;
                        }
                        leftmostthumb=newleftmostthumb;
                        if (stillloadingnewimages) {
                            carouselscrolling=false;
                        }
                        else {
                            stillloadingnewimages=true;
                            var newcarouselheight=$(thisflickrgallery).find("div.carousel-holder").height();
                            var newcarouselwidth=$(thisflickrgallery).find("div.carousel-holder").width();
                            $(thisflickrgallery).find("div.carousel-stage").css({width: newcarouselwidth, top: parseInt(-((previousleftmostthumb/4)*(newcarouselheight/2)))});
                            $(thisflickrgallery).find("div.carousel").css({width:newcarouselwidth, height: newcarouselheight, display:"block"});
                            $(thisflickrgallery).find("div.carousel-stage").animate({top: parseInt(-((leftmostthumb/4)*(newcarouselheight/2)))}, 500, function() {
                                if (loadingnewthumbs) {
                                    pagenum++;
                                    $.post("/assets/ajax/getuserflickrimages.php", { username: flickrusername, pagenum: pagenum, userid: userId, gallerytype: gallerytype }, function(xml) {
                                        var numofxmlimages=$(xml).find("image").length;
                                        if ($(xml).find("thumb-src:eq(0)").text()==$(thisflickrgallery).find("div.carousel-stage img:eq(0)").attr("src")) {
                                            pagenum--;
                                            stillloadingnewimages=false;
                                            return false;
                                        }
                                        var previousnumofimages=numofimages;
                                        numofimages+=numofxmlimages;
                                        var insertHTML="";
                                        for (var counter=0; counter<numofxmlimages; counter++) {
                                            if ((((previousnumofimages+1)+counter) % 4)==0) {
                                                insertHTML+='<div class="end-image"><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("image-src:eq("+counter+")").text()+'#'+$(xml).find("image-width:eq("+counter+")").text()+'#'+$(xml).find("image-height:eq("+counter+")").text()+'" /></div>';
                                            }
                                            else {
                                                insertHTML+='<div><img src="'+$(xml).find("thumb-src:eq("+counter+")").text()+'" alt="" name="'+$(xml).find("image-src:eq("+counter+")").text()+'#'+$(xml).find("image-width:eq("+counter+")").text()+'#'+$(xml).find("image-height:eq("+counter+")").text()+'" /></div>';
                                            }
                                        }
                                        $(thisflickrgallery).find("div.carousel-stage").append(insertHTML);
                                        updateCarouselDisplayImages();
                                        // initialisethumbnails(thisflickrgallery);
                                        stillloadingnewimages=false;
                                    });
                                }
                                else {
                                    stillloadingnewimages=false;
                                }
                                // Now update the display images
                                updateCarouselDisplayImages();
                                $(thisflickrgallery).find("div.carousel").css({display:"none"});
                                carouselscrolling=false;
                            });
                        }
                        return false;
                    });

                    $(thisflickrgallery).find("div.control-holder a.left-button").click( function() {
                        if (carouselscrolling) {
                            return false;
                        }
                        carouselscrolling=true;
                        var previousleftmostthumb=leftmostthumb;
                        var displayedthumbnails=4;
                        var newleftmostthumb=leftmostthumb-displayedthumbnails;
                        if (newleftmostthumb<0) {
                            newleftmostthumb=0;
                        }
                        leftmostthumb=newleftmostthumb;
                        var newcarouselheight=$(thisflickrgallery).find("div.carousel-holder").height();
                        var newcarouselwidth=$(thisflickrgallery).find("div.carousel-holder").width();
                        $(thisflickrgallery).find("div.carousel-stage").css({width: newcarouselwidth, top: parseInt(-((previousleftmostthumb/4)*(newcarouselheight/2)))});
                        $(thisflickrgallery).find("div.carousel").css({width:newcarouselwidth, height: newcarouselheight, display:"block"});
                        $(thisflickrgallery).find("div.carousel-stage").animate({top: parseInt(-((leftmostthumb/4)*(newcarouselheight/2)))}, 500, function() {
                            // Now update the display images
                            updateCarouselDisplayImages();
                            $(thisflickrgallery).find("div.carousel").css({display:"none"});
                            carouselscrolling=false;
                        });
                        return false;
                    });

                });
            }
            else {
                // error message;
            }
        return false;
        });
        $(parentWidget).find("div.options-holder form.create-gallery").bind("submit", loadnewgallery);
        $(parentWidget).find("div.options-holder form.create-gallery input.flickr-name").val($(parentWidget).parent().find("span.widget-info-setting").text());
        if ($(parentWidget).find("div.options-holder form.create-gallery input.flickr-name").val()) {
            $(parentWidget).find("div.options-holder form.create-gallery").submit();
        }
        else if (hasuploadgallery) {
            $(parentWidget).find("div.options-holder form.create-gallery input.upload-gallery-type").click();
            $(parentWidget).find("div.options-holder form.create-gallery").submit();

            $(parentWidget).find("div.options-holder").css({height:0});
            $(parentWidget).find("div.options-holder input.gallery-type").each( function() {
                if (this.className.indexOf("flickr") != -1) {
                    $(this).attr("checked", "");
                 }
                 else {
                    $(this).attr("checked", "checked");
                 }
            });
        }
    });

    /* BOUND FUNCTION: initialiseGallery() by Alex Kearns
     *
     * This funciton is bound to all standard gallery widgets. It automatically sets up all the gallery specific,
     * controls, ajax calls, etc for a particular widget. New standard gallery widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.gallery-holder").each( initialiseGallery = function() {
        var currentimage=0;
        var currentlyFading=false;
        var imagewidth=$(this).find("img.gallery-main-picture").width();
        var imageheight=$(this).find("img.gallery-main-picture").height();
        var numimages=$(this).find("div.gallery-stage img").length;
        $(this).find("div.gallery-stage img").css({width:imagewidth, height:imageheight});
        $(this).find("div.gallery-stage").css({height:imageheight,width:(imagewidth*numimages+10)});
        $(this).css({position: "relative"}); // Needed for safari
            $(this).find("img.gallery-main-picture").unbind(); // Needed for IE
            $(this).find("img.gallery-main-picture").click( function() {
                if (currentlyFading) {
                    return;
                }
                currentlyFading=true;
                imagewidth=$(this).parent().find("img.gallery-main-picture").width();
                imageheight=$(this).parent().find("img.gallery-main-picture").height();
                numimages=$(this).parent().find("div.gallery-stage img").length;
                $(this).parent().find("div.gallery-stage img").css({width:imagewidth, height:imageheight});
                $(this).parent().find("div.gallery-stage").css({height:imageheight, width:(imagewidth*numimages+10)});
                currentimage++;
                if (currentimage >(numimages-1)) {
                    currentimage=0;
                }
                $(this).parent().find("div.gallery-stage").css({left: -(currentimage*imagewidth)+10});
                $(this).parent().find("div.gallery-stage").animate({left: -(currentimage*imagewidth)},800);
                    $(this).animate({opacity: 0},1000, function() {
                        $(this).attr("src", $(this).parent().find("div.gallery-stage img:eq("+currentimage+")").attr("src"));
                        var mainimage=this;
                        setTimeout( function() {
                            $(mainimage).css({opacity: 1});
                            currentlyFading=false;
                        },500);
                    });
            });
    });

    /* BOUND FUNCTION: initialiseRadioPlayer() by Alex Kearns
     *
     * This funciton is bound to all radio widgets. It automatically sets up all the flickr specific,
     * controls, ajax calls, etc for a particular radio element. New radio widgets should have
     * this function attached and then called to initialise them.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.radio-player").each( initialiseRadioPlayer = function() {
        var lastsong;
        var musicid=getUniqueMusicId();
        var thisradioplayer=this;
        // store the musicid in the name tag of the a element
        $(this).find("a.pause-resume").attr("name",musicid);
        var pauseAllMusic = function() {
            soundManager.stopAll();
            $("div#drag-column-holder div.radio-player").each( function() {
                if (this==thisradioplayer) {
                    return;
                }
                if ($(this).find("a.pause-resume").text()=="Pause") {
                    soundManager.pause($(this).find("a.pause-resume").attr("name"));
                    $(this).find("a.pause-resume").text("Resume");
                }
            });
        }
        $(this).find("a.pause-resume").click( function() {
            if ($(this).text()=="Pause") {
                soundManager.pause(musicid);
                $(this).text("Resume");
            }
            else if ($(this).text()=="Resume") {
                pauseAllMusic();
                soundManager.resume(musicid);
                $(this).text("Pause");
            }
            else if ($(this).text()=="Replay") {
                pauseAllMusic();
                soundManager.play(musicid);
                $(this).text("Pause");
            }
            return false;
        });
        $(this).find("select").change( function() {
            var selectedsong=$(this).attr("value");
            if (!selectedsong) {
                return;
            }
            if (lastsong) {
                soundManager.destroySound(lastsong);
            }
            pauseAllMusic();
            lastsong=musicid;
            $(thisradioplayer).find("h2 span").text(this.options[this.selectedIndex].innerHTML);
            this.selectedIndex=0;
            $(thisradioplayer).find("a.pause-resume").text("Pause");
            $(thisradioplayer).find("div.progress-bar span").css({width: 0});
            $(thisradioplayer).find("div.radio-player div.loading-bar span").css({width: 0});
            var soundPos;
            var soundBytes;
            var loadedBytes;
            var playFinished = function() {
                $(thisradioplayer).find("div.progress-bar span").css({width: "100%"});
                $(thisradioplayer).find("div.radio-player div.loading-bar span").css({width: "100%"});
                $(thisradioplayer).find("a.pause-resume").text("Replay");
            }
            var playPosition = function() {
                loadedBytes=this.bytesLoaded;
                soundBytes=this.bytesTotal;
                soundPos=this.position;
                var soundlength=soundBytes/loadedBytes*this.duration;
                var percentfinished=soundPos/soundlength;
                $(thisradioplayer).find("div.progress-bar span").css({width: ""+parseInt(percentfinished*100)+"%"});
            }
            var loadingPosition = function() {
                loadedBytes=this.bytesLoaded;
                soundBytes=this.bytesTotal;
                $(thisradioplayer).find("div.loading-bar span").css({width: ""+parseInt(loadedBytes/soundBytes*100)+"%"});
            }
            soundManager.createSound({
               'id': lastsong,
               'url': selectedsong,
               'stream': true,
               'autoLoad': true,
               'autoPlay': true,
               'whileloading': loadingPosition,
               'whileplaying': playPosition,
               'onfinish': playFinished
              });
        });
    });


    /* MOUSEMOVE FUNCTION by Alex Kearns
     *
     * This is the main function which is called when a widget is being dragged. It is called
     * each time the mouse moves when an element is being dragged. It not only moves (drags) the
     * dragged widget to the correct position in relation to the mouse but also displays
     * the widget spacer boxes (ie, the boxes that show where the widget would go if it was dropped)
     ************************************************************************************************/
    $(document).mousemove( function(e) {
        if (!drag)
            return;
        var mouseposition=checkwhere(e);
        var yOffsetIE=0;

        $(dragelement).css({ left: mouseposition[0]-elementoffset[0], top: mouseposition[1]-elementoffset[1]});
        var numofcolumns=columnArray.length;
        var hovercolumn=false;
        var columnnum=-1;
        if (isSafari3) {
        	mouseposition[1]+=pageScrollY();
        }

        // Now pretend mouseposition is at centre widthwise of widget
        mouseposition[0]+=centreposition[0];
        for (var columncounter=0; columncounter<numofcolumns; columncounter++) {
            if ((mouseposition[1] > columnArray[columncounter].y) && (mouseposition[1] < (columnArray[columncounter].y2)) && (mouseposition[0] > columnArray[columncounter].x) && (mouseposition[0] < (columnArray[columncounter].x2))) {
            hovercolumn=columnArray[columncounter].columnId;
            columnnum=columncounter;
            break;
            }
        }
        if (hovercolumn) {
            var widgetArray=columnArray[columnnum].widgetArray;
            var numofwidgets=widgetArray.length;
            var hoverwidget=false;
            var widgetnum=-1;
            var prependwidget=false;
            var appendwidget=false;
            var yoffset;
            for (var counter=0; counter<numofwidgets; counter++) {
                yoffset=0;
                if(columnnum==widgetSpacerPos[0] && counter>=widgetSpacerPos[1]) {
                    yoffset=widgetSpacerHeight;
                }
                if(columnnum==originalWidgetInfo[0] && counter>=(originalWidgetInfo[1])) {
                    yoffset=yoffset-originalWidgetInfo[2];
                }
                if ((mouseposition[1] > (yoffset+widgetArray[counter].y)) && (mouseposition[1] < (yoffset+widgetArray[counter].y2))) {
                    hoverwidget=widgetArray[counter].widgetId;
                    widgetnum=counter;
                    if (mouseposition[1]< (yoffset+widgetArray[counter].y+50)) {
                        prependwidget=true;
                    }
                    else {
                        appendwidget=true;
                    }
                    break;
                }
            }

            if ((prependwidget && (prependwidget != previousWidgetPrepend)) || (appendwidget && (appendwidget != previousWidgetAppend)) || (hoverwidget && !((lastHoverWidget == widgetnum) && (lastHoverColumn == columnnum)))) {
                if (isFireFox || (!isIE && !widgetSpacerHeight)) {
                    widgetSpacerHeight=$(draggedelement).height()-browserHeightOffset;
                }
                $("div#widget-spacer").remove();
                var newwidgspacer=$('<div id="widget-spacer"></div>');

                $(newwidgspacer).css({height:widgetSpacerHeight});
                $(newwidgspacer).css({display:"block"});
                if (prependwidget==1) {
                    $(hoverwidget).before($(newwidgspacer))
                }
                else {
                    $(hoverwidget).after($(newwidgspacer))
                }
                lastHoverWidget=widgetnum;
                lastHoverColumn=columnnum;
                widgetSpacerPos[0]=columnnum;
                widgetSpacerPos[1]=(widgetnum+1-prependwidget);
                previousWidgetAppend=appendwidget;
                previousWidgetPrepend=prependwidget;
                return false;
            }
            if ((!hoverwidget && !((lastHoverWidget == 99999) && (lastHoverColumn == columnnum))) && numofwidgets != 0) {
                if ((mouseposition[1]-yoffset) > columnArray[columnnum].widgetArray[columnArray[columnnum].widgetArray.length-1].y2) {

                    if (!isIE) {
                        widgetSpacerHeight=$(draggedelement).height()-browserHeightOffset;
                    }
                    $("div#widget-spacer").remove();
                    $(hovercolumn).append('<div id="widget-spacer"></div>')
                    $("div#widget-spacer").css({height:widgetSpacerHeight});
                    $("div#widget-spacer").css({display:"block"});
                    lastHoverWidget=99999;
                    lastHoverColumn=columnnum;
                    widgetSpacerPos[0]=columnnum;
                    widgetSpacerPos[1]=99999;
                }
           return false;
            }
            if ((((originalWidgetInfo[0]==columnnum) && (columnArray[columnnum].widgetArray.length==1)) || numofwidgets==0 ) && (lastHoverColumn != columnnum)) {
                if (!isIE) {
                    widgetSpacerHeight=$(draggedelement).height()-browserHeightOffset;
                }
                $("div#widget-spacer").remove();
                $(hovercolumn).append('<div id="widget-spacer"></div>')
                $("div#widget-spacer").css({height:widgetSpacerHeight});
                $("div#widget-spacer").css({display:"block"});
                lastHoverWidget=99999;
                lastHoverColumn=columnnum;
                widgetSpacerPos[0]=columnnum;
                widgetSpacerPos[1]=99999;
                return false;
            }
        }

    /* $("div#variables").text("Column: "+columnnum+" Widget: "+widgetnum+" LastW:"+columnArray[columnnum].widgetArray[columnArray[columnnum].widgetArray.length-1].y2+" MouseY:"+mouseposition[1]+" Num widg:"+columnArray[columnnum].widgetArray.length+" Prepend:"+prependwidget+" yoffset:"+yoffset+" origwidth:"+originalWidgetInfo[2]+" spacerhieght:"+widgetSpacerHeight+" offset"+debug1);*/
    return false;
    });


    /* DRAG START FUNCTION by Alex Kearns
     *
     * This function is called when a user first starts to drag an element - ie on mousedown on the drag area.
     * The functions creates a clone of the dragged element, hides the original element, changes the opacity of
     * the cloned element, and finally displays a widget spacer block (the box where the widget would drop into
     * if dropped now). Note that it is actually the cloned element that is dragged, not the original widget
     * which is simply hidden during the drag process and redisplayed at the cottect position when the
     * drag element is dropped.
     ************************************************************************************************/
    $(".draggable").mousedown( widgetDropFunction=function(event) {
        if (currentlyKilling) {
            return false;
        }
        if (currentlyAnimatingWidget) {
            return false;
        }
        if ($("div#drag-column-holder div.column:eq(0)").width() != lastColumnWidth) {
            precalculateWidgetCoords();
        }
        $("div#drag-column-holder").css({height:$("div#drag-column-holder").height()});
        draggedelement=$(this).parent().get()[0];
        $(draggedelement).find("span.drag-function").click();
        var mouseposition=checkwhere(event);
        elementoffset=checkoffset(event,draggedelement);
        originalposition=[mouseposition[0]-elementoffset[0], mouseposition[1]-elementoffset[1]];
        centreposition=[(parseInt($(draggedelement).width()/2)-elementoffset[0]),(parseInt($(draggedelement).height()/2)-elementoffset[1])];
        var originalelement=$(draggedelement);
        $(draggedelement).clone().each( function() {
            dragelement=$(this);
            $(this).css({ opacity: 0.8, position: "absolute", cursor: "move", left: mouseposition[0]-elementoffset[0], top: mouseposition[1]-elementoffset[1], width: $(originalelement).width(), height: $(originalelement).height()}).prependTo("body");
            if ($(this).find("div.video-gallery-holder").length > 0) {
                $(this).find("div.video-embed-holder span").empty().append('<img src="assets/ui/video-widget/sample.video.jpg" alt=""/>');
            }
            if ($(this).find("div.douglas-gallery-holder").length > 0) {
                $(this).find("div.video-embed-holder span").empty().append('<img src="assets/ui/douglas-widget/sample.video.jpg" alt=""/>');
            }
            // Remove shadows and select from ie6 on drag;
            if (isIE && !isIE7) {
                $(this).find("div.top-shadow").css({visibility: "hidden"});
                $(this).find("select").css({visibility: "hidden"});
                $(this).find("div.competition-win-graphic").css({visibility: "hidden"});
            }
            if (isIE) { // Hide menu from all IEs plus remove popup messages
                $(this).find("div.option-menu").css({display: "none"});
                // $(this).find("div.widget-error-message a.close-message").click();
            }
            $(this).css("z-index","100");
        });

        if ($("div#widget-spacer").length > 0) {
            $("div#widget-spacer").remove();
        }
        var tempwidge=$('<div id="widget-spacer"></div>');
        widgetSpacerHeight=($(draggedelement).height())-2;
        $(tempwidge).css({position:"absolute"});
        $(tempwidge).css({display:"block"});
        $(draggedelement).css({display:"none"}).after(tempwidge);
        $(tempwidge).css({position:"static",height:widgetSpacerHeight});

        var thiswidgpos=findWidgetPos(draggedelement);
        lastHoverWidget=thiswidgpos[1];
        lastHoverColumn=thiswidgpos[0];
        widgetSpacerPos=[thiswidgpos[0],thiswidgpos[1]];

        originalWidgetInfo=[thiswidgpos[0],thiswidgpos[1], widgetSpacerHeight];
        drag=true;

    return false;
    });

    /* Cancels the default click action with this element
     ************************************************************************************************/
    $("a.draggable").click( function() {
        return false;
    });

    /* DRAG END FUNCTION by Alex Kearns
     *
     * This function is called when a dragged widget is dropped.
     *
     * It works in two wasy. When dealing with an existing widget, the function removes the
     * dragged element (which, you will remember, is a clone of the original widget), and redisplays the
     * original widget in the correct position.
     * When dealing with a new widget (ie, one that has been dragged from the select widget area), the
     * function works differently. In this case, it inserts the new widget in the correct position,
     * and then initialises it.
     ************************************************************************************************/
    $(document).mouseup( function(e) {
        if (!drag) {
            return;
        }
        drag=false;
        currentlyAnimatingWidget=true;
        if (newDragWidget) {
            if ($("div#widget-spacer").length==0) {
                $(dragelement).css({height:$(draggedelement).height(), width:$(draggedelement).width()});
                $(dragelement).animate({ left: (originalposition[0]), top: (originalposition[1]) }, 300,"", function() {
                    $(this).remove();
                    $(draggedelement).remove();
                    currentlyAnimatingWidget=false;
                });
            newDragWidget=false;
            return;
            }
        }
        var scrolltocoords=findPos($("div#widget-spacer").get()[0]);
        if (!isIE) {
            $(dragelement).css({height:$(draggedelement).height(), width:$("div#drag-column-holder div.column:eq(0)").width()});
        }
        var drageltopleft = new Array();
        drageltopleft[0]=checkwhere(e)[0]-elementoffset[0];
        drageltopleft[1]=checkwhere(e)[1]-elementoffset[1];
        var scrolltodistance = Math.abs(((drageltopleft[0]-scrolltocoords[0])*(drageltopleft[1]-scrolltocoords[1])));
        var scrolltime=parseInt(scrolltodistance/50);
        if (scrolltime > 300) {
            scrolltime=300;
        }
        $(dragelement).animate({ left: (scrolltocoords[0]-10), top: (scrolltocoords[1]+1) }, scrolltime,"", function() {
            var databaseupdated=false;
            $(this).remove();
                 //   $(draggedelement).remove();
                 //   draggedelement=$(widgetInsertHTML);
            $(draggedelement).insertAfter("div#widget-spacer").css({display: "block"});
            $("div#widget-spacer").remove();

            if (newDragWidget) {
                newDragWidget=false;
                var newwidgethasbeenadded=true;
                if ($(draggedelement).find("div.gallery-holder").length > 0) { //This is gallery widget so initialise gallery widget functions
                    $(draggedelement).find("div.gallery-holder").bind("click", initialiseGallery);
                    $(draggedelement).find("div.gallery-holder").click();
                    $(draggedelement).find("div.gallery-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.radio-player").length > 0) { //This is radio player widget so initialise radio widget functions
                    $(draggedelement).find("div.radio-player").bind("click", initialiseRadioPlayer);
                    $(draggedelement).find("div.radio-player").click();
                    $(draggedelement).find("div.radio-player").unbind("click");
                }
                else if ($(draggedelement).find("div.video-gallery-holder").length > 0) { //This is radio player widget so initialise radio widget functions
                    $(draggedelement).find("div.video-gallery-holder").bind("click", initialiseVideoGallery);
                    $(draggedelement).find("div.video-gallery-holder").click();
                    $(draggedelement).find("div.video-gallery-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.flickr-gallery-holder").length > 0) { //This is Video player so initialise videoplayer functions
                    $(draggedelement).find("div.flickr-gallery-holder").bind("click", initialiseFlickrGallery);
                    $(draggedelement).find("div.flickr-gallery-holder").click();
                    $(draggedelement).find("div.flickr-gallery-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.calendar-widget-holder").length > 0) { //This is Calendar widget so initialise calendar widget functions
                    /* Note that is different from previous versions */
                    /* $(draggedelement).remove();
                    draggedelement=$(widgetInsertHTML); */
                    $(draggedelement).find("div.calendar-widget-holder").bind("click", initialiseCalendarWidget);
                    $(draggedelement).find("div.calendar-widget-holder").click();
                    $(draggedelement).find("div.calendar-widget-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.music-reviews-widget-holder").length > 0) { //Music reviews widget so initialise music reviews functions
                    $(draggedelement).find("div.music-reviews-widget-holder").bind("click", initialiseMusicReviewsWidget);
                    $(draggedelement).find("div.music-reviews-widget-holder").click();
                    $(draggedelement).find("div.music-reviews-widget-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.music-news-widget-holder").length > 0) { //Music news widget so initialise music news functions
                    $(draggedelement).find("div.music-news-widget-holder").bind("click", initialiseMusicNewsWidget);
                    $(draggedelement).find("div.music-news-widget-holder").click();
                    $(draggedelement).find("div.music-news-widget-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.welcome-widget-holder").length > 0) { //Welcome widget so initialise music news functions
                    $(draggedelement).find("div.welcome-widget-holder").bind("click", initialiseWelcomeWidget);
                    $(draggedelement).find("div.welcome-widget-holder").click();
                    $(draggedelement).find("div.welcome-widget-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.competition-widget-holder").length > 0) { //Competition widget so initialise competition widget functions
                    $(draggedelement).find("div.competition-widget-holder").bind("click", initialiseCompetitionWidget);
                    $(draggedelement).find("div.competition-widget-holder").click();
                    $(draggedelement).find("div.competition-widget-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.cool-links-widget-holder").length > 0) { //Cool links widget so initialise cool links functions
                    $(draggedelement).find("div.cool-links-widget-holder").bind("click", initialiseCoolLinksWidget);
                    $(draggedelement).find("div.cool-links-widget-holder").click();
                    $(draggedelement).find("div.cool-links-widget-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.douglas-gallery-holder").length > 0) { //Michael Douglas widget so initialise Michael Douglas functions
                    $(draggedelement).find("div.douglas-gallery-holder").bind("click", initialiseDouglasGallery);
                    $(draggedelement).find("div.douglas-gallery-holder").click();
                    $(draggedelement).find("div.douglas-gallery-holder").unbind("click");
                }
                else if ($(draggedelement).find("div.product-promotion-widget-holder").length > 0) { //Michael Douglas widget so initialise Product promotion
                    $(draggedelement).find("div.product-promotion-widget-holder").bind("click", initialisePromotionWidget);
                    $(draggedelement).find("div.product-promotion-widget-holder").click();
                    $(draggedelement).find("div.product-promotion-widget-holder").unbind("click");
                }
				else if ($(draggedelement).find("div.nmeipod-widget-holder").length > 0) { //NME iPod Touch widget
                    $(draggedelement).find("div.nmeipod-widget-holder").bind("click", initialiseNmeiPod);
                    $(draggedelement).find("div.nmeipod-widget-holder").click();
                    $(draggedelement).find("div.nmeipod-widget-holder").unbind("click");
                }
                // Add the standard events to the widgets components
                $(draggedelement).find("div.draggable").bind("mousedown",widgetDropFunction);
                $(draggedelement).find("a.kill-widget").unbind().bind("mousedown",widgetKillMouseDown);
                $(draggedelement).find("a.kill-widget").bind("click",widgetKillFunction);
                $(draggedelement).find("a.minimise-widget").unbind().bind("mousedown",widgetKillMouseDown);
                $(draggedelement).find("a.minimise-widget").bind("click",widgetMinimise);
                $(draggedelement).find("a.widget-menu-button").unbind().bind("mousedown",widgetKillMouseDown);
                $(draggedelement).find("a.widget-menu-button").bind("click",widgetMenu);
                $(draggedelement).find("div.option-menu a").unbind().bind("click",openCloseOptions);
                $(draggedelement).find("div.options-holder a.options-close-button").unbind().bind("click",optionsCloseButton);
                $(draggedelement).find("div.widget-colour-chooser div.inkwell").unbind().bind("click",changeWidgetColour);

                // Now update new widget in database if user logged in
                if (userId !=="") {
                    // May need a closure here
                    databaseupdated=true;

                    (function(){
                        var newwidgetposition=lastHoverColumn*100;
                        if (previousWidgetPrepend) {
                            newwidgetposition+=lastHoverWidget;
                        }
                        else {
                            newwidgetposition+=(lastHoverWidget+1);
                        }
                        var newwidgettype=global_widgettypes[$(draggedelement).find("span.widget-info-type").text()];
                        var newwidgetcolour=global_widgetcolours[$(draggedelement).find("span.widget-info-colour").text()];
                        var newwidgetsetting=$(draggedelement).find("span.widget-info-setting").text();

                        var newwidgetinfo=newwidgettype+"#"+newwidgetposition+"#"+newwidgetcolour+"#"+newwidgetsetting;
                        $.post("assets/ajax/state-add-widget.php", { userid: userId, widgetinfo: newwidgetinfo}, function(data) {
                            $(draggedelement).find("span.widget-info-id").text(data);
                            updatemovedwidgets();
	            			// Now update stats for when a logged in user adds a widget
		                	$.post("assets/ajax/statistics-widget.php", { action: "add", widgettype: newwidgettype});
                        });
                    })();
                }

                else {
                	// Now update stats for when a NON-logged in user adds a widget	
		                var newwidgettype=global_widgettypes[$(draggedelement).find("span.widget-info-type").text()];
		                $.post("assets/ajax/statistics-widget.php", { action: "add", widgettype: newwidgettype});
                }
            }
            if (isIE) {
                var tallestcolumn=$("div#drag-column-holder div.column:eq(0)").height();
                if (tallestcolumn<$("div#drag-column-holder div.column:eq(1)").height()) {
                    tallestcolumn=$("div#drag-column-holder div.column:eq(1)").height();
                }
                if (tallestcolumn<$("div#drag-column-holder div.column:eq(2)").height()) {
                    tallestcolumn=$("div#drag-column-holder div.column:eq(2)").height();
                }
                $("div#drag-column-holder").css({height:tallestcolumn});
            }
            else {
                $("div#drag-column-holder").css({height:"auto"});
            }
            $(draggedelement).find("span.drop-function").click();
            precalculateWidgetCoords();
            lastHoverWidget=-1;
            currentlyAnimatingWidget=false;
            if (userId !=="" && !databaseupdated) {
                updatemovedwidgets();
            }
            if (!newwidgethasbeenadded) {
            	// if this is not a new widget, we should store move stats
            	var thismovewidgettype=global_widgettypes[$(draggedelement).find("span.widget-info-type").text()];
		        $.post("assets/ajax/statistics-widget.php", { action: "move", widgettype: thismovewidgettype});
            }
        });
    });

    /* Timeout to work out widget positions just after page load.
     *
     ************************************************************************************************/
    setTimeout( function() {
        precalculateWidgetCoords();
    },100);


    /* OPEN/CLOSE WIDGET SELECTION PANE by Alex Kearns
     *
     * This function opens or closes the widget selection pane.
     ************************************************************************************************/

    var selectionPanelSetup = function() {

        var currentlyOpeningClosing=false;
        var themeSelectFunction="";

        $("div#widget-selection-holder div#main-login-holder a.sign-in").click( function() {
            loginPopup("login-panel");
            return false;
        });

        $("div#widget-selection-holder div#main-login-holder a.sign-out").click( function() {
            Set_Cookie('shockwaves', "signedout", 30, '/', '', '' );
            window.location.reload(true);
            return false;
        });


        $("div#widget-selection-holder a.close-selection-tab").click(function() {
            if (currentlyOpeningClosing) {
                return false;
            }
            currentlyOpeningClosing=true;
            if (currentlySelectedPanel) {
                $("div#widget-selection-holder div.content-"+currentlySelectedPanel).animate({height:0},500, "easein", function() {
                    currentlySelectedPanel="";
                    $(this).css({display: "none"});
                    $("div#widget-selection-holder a.selection-tab-selected").removeClass("selection-tab-selected");
                    precalculateWidgetCoords();
                    currentlyOpeningClosing=false;
                    updatewidgetstotheme();
                });
            }
            else {
                currentlyOpeningClosing=false;
                $("div#widget-selection-holder a.modules-selection-tab").click();
            }
            return false;
        });


        $("div#widget-selection-holder a.modules-selection-tab").click(function() {
            if (currentlyOpeningClosing) {
                return false;
            }
            currentlyOpeningClosing=true;
            $(this).addClass("selection-tab-selected");
            if (currentlySelectedPanel == "modules") {
                currentlyOpeningClosing=false;
                $("div#widget-selection-holder a.close-selection-tab").click();
            }
            else if (currentlySelectedPanel == "themes") {
                $("div#widget-selection-holder div.content-themes").css({display:"none"});
                $("div#widget-selection-holder div.content-modules").css({display:"block", height: selectionPanelHeight});
                $("div#widget-selection-holder a.themes-selection-tab").removeClass("selection-tab-selected");
                currentlySelectedPanel="modules";
                currentlyOpeningClosing=false;
            }
            else if (!currentlySelectedPanel) {

                $("div#widget-selection-holder div.content-modules").css({display: "block", height: 0}).animate({height:selectionPanelHeight},500, "easein", function() {
                    currentlySelectedPanel="modules";
                    precalculateWidgetCoords();
                    currentlyOpeningClosing=false;
                });
            }
            return false;
        });

        $("div#widget-selection-holder a.themes-selection-tab").click(function() {
            if (currentlyOpeningClosing) {
                return false;
            }
            currentlyOpeningClosing=true;
            $(this).addClass("selection-tab-selected");
            if (currentlySelectedPanel == "themes") {
                currentlyOpeningClosing=false;
                $("div#widget-selection-holder a.close-selection-tab").click();
            }
            else if (currentlySelectedPanel == "modules") {
                $("div#widget-selection-holder div.content-modules").css({display:"none"});
                $("div#widget-selection-holder div.content-themes").css({display:"block", height: selectionPanelHeight});
                $("div#widget-selection-holder a.modules-selection-tab").removeClass("selection-tab-selected");
                currentlySelectedPanel="themes";
                currentlyOpeningClosing=false;
            }
            else if (!currentlySelectedPanel) {
                $("div#widget-selection-holder div.content-themes").css({display: "block", height: 0}).animate({height:selectionPanelHeight},500, "easein", function() {
                    currentlySelectedPanel="themes";
                    precalculateWidgetCoords();
                    currentlyOpeningClosing=false;
                });
            }
            return false;
        });

		// Automatically open the Add stuff" layer for users not logged in
		if (userId == "") {
			setTimeout( function() {
				currentlyOpeningClosing=false;
				$("div#widget-selection-holder a.modules-selection-tab").click();
			}, 1500);
		}

        $("div#widget-selection-holder div.content-themes div.theme-selector a").click( themeSelectFunction = function() {

            var numofthemes=$("div#widget-selection-holder div.content-themes div.theme-selector span.theme-class").length;

            for (var counter=0; counter<numofthemes; counter++) {
                var themeclass=$("div#widget-selection-holder div.content-themes div.theme-selector span.theme-class:eq("+counter+")").text();
                $("body").removeClass(themeclass);
            }
            $("body").addClass($(this).parents("div.theme-selector").find("span.theme-class").text());
            selectedTheme=$(this).parents("div.theme-selector").find("span.theme-class").text();

            var selectedcolourscheme=$(this).parents("div.theme-selector").find("span.theme-colour").text();
            $("div.widget").each(function() {
                $(this).removeClass("widget-purple");
                $(this).removeClass("widget-grey");
                $(this).removeClass("widget-green");
                $(this).removeClass("widget-red");
                $(this).removeClass("widget-lgreen");
                $(this).removeClass("widget-orange");
                $(this).addClass("widget-"+selectedcolourscheme);
                $(this).find("span.widget-info-colour").text(selectedcolourscheme);
            });

            $("div#widget-selection-holder").removeClass("selection-theme-purple");
            $("div#widget-selection-holder").removeClass("selection-theme-grey");
            $("div#widget-selection-holder").removeClass("selection-theme-green");
            $("div#widget-selection-holder").removeClass("selection-theme-red");
            $("div#widget-selection-holder").removeClass("selection-theme-lgreen");
            $("div#widget-selection-holder").removeClass("selection-theme-orange");
            $("div#widget-selection-holder").addClass("selection-theme-"+ selectedcolourscheme);
            return false;
        });

        $("div#widget-selection-holder div.content-themes div.theme-selector img").bind("click", themeSelectFunction);

    }
    selectionPanelSetup();



    /* This unbinds the mousedown call on the kill widget button to prevent the drag event
     * cascading down to the drar widget (hook) area.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget a.kill-widget").unbind().mousedown( widgetKillMouseDown = function() {
        return false;
    });

    $("div#drag-column-holder div.widget a.minimise-widget").unbind().mousedown( function() {
        return false;
    });

    $("div#drag-column-holder div.widget a.widget-menu-button").unbind().mousedown( function() {
        return false;
    });



    /* MINIMISE WIDGET FUNCTION by Alex Kearns
     *
     * This function is called when the widget minimise button is pressed.
     * The function either animates the content area to height zero and then displats none
     * Or if the widget has already been minimised, it animates the content area to its height
     * Some of the code deals with wierd IE6 bugs effecting the position of the top shadow
     ************************************************************************************************/
    $("div#drag-column-holder div.widget a.minimise-widget").unbind("click").click( widgetMinimise=function() {
        if (currentlyAnimatingWidget) {
            return false;
        }
        currentlyAnimatingWidget=true;
        var thisparentwidget=$(this).parents("div.widget");

        if (isIE && !isIE7) {
            var contentheight=$(this).parent().parent().find("div.content").css({overflow:"visible"}).height();
            if (isIE6) {
                $(this).parent().parent().find("div.top-shadow").css({left: 3});
                $(this).parent().parent().find("div.option-menu").css({right: 3});
            }
            if ($(this).parent().parent().find("div.content").css("display")=="block") {
                // Call widget specific function to respond to minimise
                $(thisparentwidget).find("span.minimise-function").click();
                $(this).parent().parent().find("div.content").css({height:contentheight}).animate({height:0}, function() {
                    $(this).css({display:"none", height:0});
                    $(this).css({overflow:"hidden"});
                    $(thisparentwidget).find("a.widget-menu-button").css({visibility: "hidden"});
                    precalculateWidgetCoords();
                    currentlyAnimatingWidget=false;
                });
            }
            else {
                $(this).parent().parent().find("div.content").animate({height:contentheight}, function() {
                    $(this).css({display:"block",height:0});
                    $(this).css({overflow:"visible"});
                    $(thisparentwidget).find("a.widget-menu-button").css({visibility: "visible"});
                    // Call widget specific function to respond to minimise
                    $(thisparentwidget).find("span.unminimise-function").click();
                    precalculateWidgetCoords();
                    currentlyAnimatingWidget=false;
                });
            }
        }
        else {
            if ($(this).parent().parent().find("div.content").css("display")=="block") {
                // Call widget specific function to respond to minimise
                $(thisparentwidget).find("span.minimise-function").click();
                $(this).parent().parent().find("div.content").slideUp(500, function() {
                    if (isIE7) {
                        $(thisparentwidget).find("a.widget-menu-button").css({visibility: "hidden"});
                    }
                    else {
                        $(thisparentwidget).find("a.widget-menu-button").css({opacity: 0.25});
                    }
                    $(this).css({display:"none"});
                    precalculateWidgetCoords();
                    currentlyAnimatingWidget=false;
                });
            }
            else {
                $(this).parent().parent().find("div.content").slideDown(500, function() {
                    if (isIE7) {
                        $(thisparentwidget).find("a.widget-menu-button").css({visibility: "visible"});
                    }
                    else {
                        $(thisparentwidget).find("a.widget-menu-button").css({opacity: 1});
                    }
                    $(this).css({display:"block"});
                    // Call widget specific function to respond to minimise
                    $(thisparentwidget).find("span.unminimise-function").click();
                    precalculateWidgetCoords();
                    currentlyAnimatingWidget=false;
                });
            }
        }
        return false;
    }).click( function() { return false });

    /* SHOW WIDGET MENU by Alex Kearns
     *
     * This funciton is called when the widget menu button is mousedowned.
     * It works in two ways. If the options content area, is not showing it either displays of
     * hides the menu.
     * Alternatively, if the options content area is visible and the menu is invisible, it hides the options
     * area and displays the menu.  All elements are displayed and hidden via slideups/slidedowns
     ************************************************************************************************/
    $("div#drag-column-holder div.widget a.widget-menu-button").unbind("click").click( widgetMenu=function() {
        var parentwidget=$(this).parent().parent();
        if ($(parentwidget).find("div.content").css("display")=="none") {
            // If the widget is minimised, simpley return;
            return false;
        }
        var optionsmenu=$(parentwidget).find("div.option-menu");
        if ($(optionsmenu).attr("title")=="animating") {
            return false;
        }
        // Original set up
        if ($(optionsmenu).css("display")=="none") {
            $(optionsmenu).css({visibility:"hidden"}).css({display:"block"});
            $(optionsmenu).css({height: ($(optionsmenu).find("div").height())});
            $(optionsmenu).find("div").css({top: -($(optionsmenu).find("div").height())});
            $(optionsmenu).css({visibility:"visible"}).css({display:"none"});
        }
        // Now do animations
        $(optionsmenu).attr("title","animating");
        if ($(optionsmenu).css("display")=="block") {
            $(optionsmenu).find("div").animate({top: -($(optionsmenu).find("div").height())},500, function() {
                $(optionsmenu).css({display: "none"}).attr("title","");
            });
        }
        else {
            $(optionsmenu).css({display: "block"}).find("div").animate({top: 0},500, function() {
                $(optionsmenu).attr("title","");
            });
        }
        if ($(parentwidget).find("div.options-holder").css("display")=="block") {
            $(parentwidget).find("div.options-holder").animate({height: 0},500, function() { $(this).css({display:"none"}) });
        }

        return false;
    }).click( function() { return false });


    /* CLOSE OPTIONS AREA  by Alex Kearns
     *
     * This funciton is called when the close cross on the option area is clicked.
     * It simply hides the option area via a slide-up
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.options-holder a.options-close-button").unbind().click( optionsCloseButton=function() {
        $(this).parent().animate({height: 0},500, function() {
            $(this).css({display:"none"});
            precalculateWidgetCoords();
        });
        return false;
    });


    /* SHOW OPTIONS AREA  by Alex Kearns
     *
     * This funciton is called when a item  is selected on the widget menu.
     * It slides down the options area to its full height. The function relies on the
     * specialFindHeight function to find out how tall the options area should be.
     ************************************************************************************************/
    $("div#drag-column-holder div.widget div.option-menu a").unbind("click").click( openCloseOptions=function() {
        var parentwidget=$(this).parent().parent().parent().parent().parent().get()[0];
        var optionsmenu=$(parentwidget).find("div.option-menu");
        $(optionsmenu).find("div").animate({top: -($(optionsmenu).find("div").height())},500, function() {
            $(optionsmenu).css({display: "none"}).attr("title","");
        });
        $(parentwidget).find("div.options-holder li").css({display:"none"});
        $(parentwidget).find("div.options-holder li:eq("+$(this).attr("name")+")").css({display:"block"});

        var newheight = specialFindHeight($(parentwidget).find("div.options-holder div.options-holder-inner"),$(parentwidget).width()-26);

        $(parentwidget).find("div.options-holder").css({display: "block"}).animate({height: newheight+40},500, function() {
            precalculateWidgetCoords();
        });
        return false;
    });


    /* KILL WIDGET FUNCTION  by Alex Kearns
     *
     * This funciton is called when the kill widget cross is clicked.
     * It removes the widget from the dom after a fade out, and then animates the resulting space to zero
     ************************************************************************************************/
    $("div#drag-column-holder div.widget a.kill-widget").click( widgetKillFunction = function() {
        currentlyKilling=true;
        var killtime=300;
        if (isIE6) {
            killtime=1;
        }
        var thisparentwidget=$(this).parents("div.widget");
        $(thisparentwidget).find("span.kill-function").click();

        var thiswidgetid = $(thisparentwidget).find("span.widget-info-id").text();
        var thiswidgettype = global_widgettypes[$(thisparentwidget).find("span.widget-info-type").text()];

        $(this).parent().parent().animate({opacity: 0}, killtime, function() {
            if(isIE6) {
                $(this).css({visibility:"hidden"});
            }
            if ($(this).find("div.radio-player a.pause-resume").text()) {
                // Radio player widget so kill music
                soundManager.stop($(this).find("div.radio-player a.pause-resume").attr("name"));
            }
            lastHoverWidget=-1;
            lastHoverColumn=-1;
            widgetSpacerPos=[99999,99999];
            $(this).animate({height:0}, 500, function() {

				if (userId != "") {
	        		$.post("assets/ajax/state-kill-widget.php", { widgetid: thiswidgetid, userid: userId }, function() {
	        			// Stats for logged in user
		        		$.post("assets/ajax/statistics-widget.php", { action: "kill", widgettype: thiswidgettype});
                });
				}
				else {
						// Stats for non-logged in user
		        		$.post("assets/ajax/statistics-widget.php", { action: "kill", widgettype: thiswidgettype});
				}
                $(this).remove();

                // This is probably not necessary
                /* setTimeout( function() {
                    updatemovedwidgets();
                },1); */

                precalculateWidgetCoords();
                currentlyKilling=false;
                if (isIE) {
                    var tallestcolumn=$("div#drag-column-holder div.column:eq(0)").height();
                    if (tallestcolumn<$("div#drag-column-holder div.column:eq(1)").height()) {
                        tallestcolumn=$("div#drag-column-holder div.column:eq(1)").height();
                    }
                    if (tallestcolumn<$("div#drag-column-holder div.column:eq(2)").height()) {
                        tallestcolumn=$("div#drag-column-holder div.column:eq(2)").height();
                    }
                    $("div#drag-column-holder").css({height:tallestcolumn});
                }
                else {
                    $("div#drag-column-holder").css({height:"auto"});
                }
            });
        });
        return false;
    });


    /* CREATE NEW WIDGET FUNCTION by Alex Kearns
     *
     * This function is called when the user creates a new widget by dragging one from the select
     * widget area. At this stage, the widget is only being dragged, having not been added to the
     * widget stage.
     ************************************************************************************************/
    $("div.widget-selector").mousedown( function(event) {
        if (currentlyKilling) {
            return false;
        }
        if (currentlyAnimatingWidget) {
            return false;
        }
        if ($("div#drag-column-holder div.column:eq(0)").width() != lastColumnWidth) {
            precalculateWidgetCoords();
        }

        var codeholderid=$(this).find("span.widget-code").text();
        var tempelement=$("div#"+codeholderid).find("div.widget").clone();
        widgetInsertHTML=$("div#"+codeholderid).html();
        draggedelement=$(tempelement).get()[0];
        $(draggedelement).css({display: "none"});
        $(draggedelement).insertAfter("div#drag-column-holder div.prevent-collapse:eq(0)");

        var mouseposition=checkwhere(event);
        elementoffset=[150,10];
        centreposition=[(parseInt($(draggedelement).width()/2)-elementoffset[0]),(parseInt($(draggedelement).height()/2)-elementoffset[1])];
        originalposition=[mouseposition[0]-elementoffset[0], mouseposition[1]-elementoffset[1]];
        var originalelement=$(draggedelement);
        $(draggedelement).clone().each( function() {
            dragelement=$(this);
            if (isIE && !isIE7) {
                $(this).find("div.top-shadow").css({visibility: "hidden"});
                $(this).find("select").css({visibility: "hidden"});
            }
            $(this).css({ opacity: 0.8, display: "block", position: "absolute", cursor: "move", left: mouseposition[0]-elementoffset[0], top: mouseposition[1]-elementoffset[1], width: lastColumnWidth, height: $(originalelement).height()}).prependTo("body");
            $(this).css("z-index","100");
            if (isIE) {
                widgetSpacerHeight=$(draggedelement).height()-12;
            }
            else {
                widgetSpacerHeight=$(draggedelement).height()-12;
            }

        });
        if ($("div#widget-spacer").length>0) {
            $("div#widget-spacer").remove();
        }
        var thiswidgpos=[99999,99999];
        lastHoverWidget=-1;
        lastHoverColumn=-1;
        widgetSpacerPos=[99999,99999];
        originalWidgetInfo=[thiswidgpos[0],thiswidgpos[1], 0];
        newDragWidget=true;
        drag=true;
    return false;
    });






    /* COLOUR CHOOSER by Alex Kearns
     *
     * This funciton changes the colour of the paraent widget.
     * It removes all colour classes from the widget and then adds a new colour class
     ************************************************************************************************/
    $("div#drag-column-holder div.widget-colour-chooser div.inkwell").click( changeWidgetColour = function() {
        var colourcode="widget-"+$(this).attr("title");
        var thisparentwidget=$(this).parents("div.widget");
        $(thisparentwidget).removeClass("widget-red");
        $(thisparentwidget).removeClass("widget-green");
        $(thisparentwidget).removeClass("widget-grey");
        $(thisparentwidget).removeClass("widget-lgreen");
        $(thisparentwidget).removeClass("widget-orange");
        $(thisparentwidget).removeClass("widget-purple");
        $(thisparentwidget).addClass(colourcode);
        $(thisparentwidget).find("span.widget-info-colour").text($(this).attr("title"));

        var thiswidgetid=$(thisparentwidget).find("span.widget-info-id").text()
        if (thiswidgetid) {
            $.post("assets/ajax/state-update-colour.php", { newcolour: global_widgetcolours[$(this).attr("title")], widgetid: thiswidgetid});
        }
    });



    // Disable kill widget button for productpromotion widget
    /* $("div.product-promotion-widget-holder").parent().parent().find("a.kill-widget").unbind("click").click (
        function() {
            return false;
        }).css({opacity: 0.3}); */



    /* if (isIE && !isIE7) {
        $("div.widget div.top-shadow").css({visibility:"visible"});
    } */


    /* UPDATE WIDGET ELEMENT HEIGHTS by Alex Kearns
     *
     * This function is called at a set interval.
     * Its aim is to ensure that the height of images in the gallery and videos in the vide gallery
     * are resized when the user resizes the window, thus changing the size of the widgets.
     ************************************************************************************************/
    setInterval( function() {
        if (drag) {
            return;
        }

        if ($("div#drag-column-holder div.column:eq(0)").width() != lastColumnWidth) {
            $("div#drag-column-holder div.video-gallery-holder").each( function() {
               $(this).find("div.video-embed-holder div").css({height: parseInt($(this).find("div.video-embed-holder").width()*350/425)});
                $(this).find("div.video-embed-holder div span").css({height: parseInt($(this).find("div.video-embed-holder").width()*350/425)});
               $(this).find("div.video-embed-holder").css({height: parseInt($(this).find("div.video-embed-holder").width()*350/425)});
            });
            $("div#drag-column-holder div.douglas-gallery-holder").each( function() {
               $(this).find("div.video-embed-holder div").css({height: parseInt($(this).find("div.video-embed-holder").width()*350/425)});
                $(this).find("div.video-embed-holder div span").css({height: parseInt($(this).find("div.video-embed-holder").width()*350/425)});
               $(this).find("div.video-embed-holder").css({height: parseInt($(this).find("div.video-embed-holder").width()*350/425)});
            });
            precalculateWidgetCoords()
        }
    },1000);

    setInterval( function() {
        updatewidgetstotheme();
    },10000);


    setTimeout( function() {
        var bodyheight=$("body").height();
        var viewportheight=getViewportDimensions()[1];
        if (bodyheight < viewportheight) {
            $("ul#footer").css({marginTop:(viewportheight-bodyheight)});
        }
            $("ul.home-footer").css({visibility: "visible"});
    }, 1);

});
