$(document).ready(function(){

    // Setup the dialogs
    $('#system_message').dialog({
        title: "Application Message",
        width: "320",
        height: "220",
        draggable: false,
        resizable: false,
        bgiframe: true,
        autoOpen: false,
        modal: false,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });

    $('#system_working').ajaxStart(function(){
        $(this).show();
    }).ajaxComplete(function(){
        $(this).fadeOut("slow");
    });

    VsignInitialise();

    // Make some buttons
    $('.SecondNav a').button();

    //get the height and width of the page
    var window_width = $(window).width();
    var window_height = $(window).height();
    
    //vertical and horizontal centering of modal window(s)
    /*we will use each function so if we have more then 1 
    modal window we center them all*/
    $('.modal_window').each(function(){
        
        //get the height and width of the modal
        var modal_height = $(this).outerHeight();
        var modal_width = $(this).outerWidth();
        
        //calculate top and left offset needed for centering
        var top = (window_height-modal_height)/2;
        var left = (window_width-modal_width)/2;
        
        //apply new top and left css values 
        $(this).css({'top' : top , 'left' : left});
        
    });

        
    $('.activate_modal').click(function(){
            
          //get the id of the modal window stored in the name of the activating element       
          var modal_id = $(this).attr('name');
          
          //use the function to show it
          show_modal(modal_id);
          
    });
    
    $('.close_modal').click(function(){
        //use the function to close it
        close_modal();
    });

});

//THE FUNCTIONS

function close_modal(){
    
    //hide the mask
    $('#mask').fadeOut(500);
    
    //hide modal window(s)
    $('.modal_window').fadeOut(500);
    
}
function show_modal(modal_id){

    //set display to block and opacity to 0 so we can use fadeTo
    $('#mask').css({ 'display' : 'block', opacity : 0});
    
    //fade in the mask to opacity 0.8 
    $('#mask').fadeTo(500,0.5);
     
     //show the modal window
    $('#'+modal_id).fadeIn(500);
    
}

/**
 * Initialises the page/form
 * @param {Object} scope (the form or page)
 */
function VsignInitialise(scope){

    // If the scope isnt defined then assume the entire page
    if (scope == undefined || scope == "") {
        scope = " ";
    }

    // Parse the langid out of the url
    if (gup("lang") != "")
    {
        // Add this lang to all the urls on the page
        // TODO: this might be slow - maybe we need a more efficient way of doing this
        $(scope + ' a').each(function(){
            $(this).attr('href', $(this).attr('href') + '&lang=' + gup("lang"));
        });

        $(scope + ' form').each(function(){
            $(this).attr('href', $(this).attr('href') + '&lang=' + gup("lang"));
        });

        $(scope + ' button').each(function(){
            $(this).attr('href', $(this).attr('href') + '&lang=' + gup("lang"));
        });
    }

    // Search for any grids on the page and render them
    $(scope + " .VsignGrid").each(function(){

        var gridId = $(this).attr("id");

        // For each one setup the filter form bindings
        $('.VsignFilter form :input', this).change(function(){
            VsignGridRender(gridId);
        });

        $('.VsignFilter form', this).submit(function(){
            // We dont actually want the form to be submittable (just in case)
            return false;
        });

        // Render
        VsignGridRender(gridId);
    });

    // Search for any Buttons / Links on the page that are used to load forms
    $(scope + " .VsignFormButton").click(function(){

        var formUrl = $(this).attr("href");

        VsignFormRender(formUrl);

        return false;
    });

    // Buatan sendiri untuk peek view
    $(scope + " .VsignPeekButton").click(function(){
        //var modal_id = $(this).attr('name');
        //var modal_id = "modal_window";
          
        //use the function to show it
        //show_modal(modal_id);
        //var formUrl = $(this).attr("href");

        //VsignPeekView(formUrl);
        var formUrl = $(this).attr("href");
        //$('#test_window').html("<p>kampret</p>");

        VsignPeekView(formUrl);
        //MyDebug(formUrl);

        return false;
    });

    // Search for any Buttons / Linkson the page that are used to load hover tooltips
    $(scope + " .VsignHoverButton").hover(
        function(e){

            var formUrl = $(this).attr("href");

            VsignHoverRender(formUrl, e.pageX, e.pageY);

            return false;
        },
        function(){

            // Dont do anything on hover off - the hover on deals with
            // destroying itself.
            return false;
        }
    );

    // Search for any forms that will need submitting
    // NOTE: The validation plugin does not like binding to multiple forms at once.
    $(scope + ' .VsignForm').validate({
        submitHandler: VsignFormSubmit
    });

    // Forms that we want to be submitted without validation.
    $(scope + ' .VsignAutoForm').submit( function() {
        VsignFormSubmit(this);

        return false;
    });

    // Search for any text forms that will need submitting
    $(scope + ' .VsignTextForm').submit(function(){
        VsignFormSubmit(this);

        return false;
    });

    // Search for any help enabled elements
    $(scope + " .VsignHelpButton").click(function(){

        var formUrl = $(this).attr("href");

        VsignHelpRender(formUrl);

        return false;
    });
}

/**
 * Peek view the captured window screen
 * @param {String} formUrl
 */
function VsignPeekView(formUrl)
{
    // Prepare the Dialog
    $('#div_dialog').dialog('destroy');
    $('#div_dialog').html("");

    // Call with AJAX
    $.ajax({
        type: "get",
        url: formUrl + "&ajax=true",
        cache: false,
        dataType: "json",
        success: function(response){
            var $lightbox, $window, a, i, imageNumber, left, top, _len, _ref;

            // Was the Call successful
            if (response.success) {

                //$('#div_dialog').after('<img src="img/lightbox/examples/image-5.jpg" alt="Plants: image 3 0f 4 thumb" />');
                VsignLightbox("img/lightbox/examples/image-5.jpg",1,1);

                // Set the dialog HTML to be the response HTML
                //$('#div_dialog').html(response.html);
                //$('#test_window').html("<p>kampret 2</p>");
                //$('#modal_window').html("kampret 2");
                //$('#modal_window').fadeIn(500);
                //$('#modal_window').html(response.html);
                //$('#modal_window').html("tes apa aja");
                //$('#div_dialog').html("tes apa aja");

                //$('#peekview').html('<img src="img/lightbox/examples/image-5.jpg" alt="Plants: image 3 0f 4 thumb" />').fadeIn(500);
                //$('#peekview').append('yuhuu....').fadeIn();
                //$lightbox = $('a[rel^=lightbox], area[rel^=lightbox]');
                //$lightbox.init();
                //show_modal('modal_window');

                // Call Vsign Init for this form
                //VsignInitialise("#modal_window");
            }
            return false;
        }
    });

    // Dont then submit the link/button
    return false;
}

function VsignLightbox(img, number, position)
{

    //var $, Lightbox, LightboxOptions;
    var Lightbox, LightboxOptions;
    //$ = jQuery;
    //console.log(img);
    //$("#peekview").html(img);

    LightboxOptions = (function() {

        function LightboxOptions() {
        this.fileLoadingImage = 'img/lightbox/loading.gif';
        this.fileCloseImage = 'img/lightbox/close.png';
        this.resizeDuration = 700;
        this.fadeDuration = 500;
        this.labelImage = "Image";
        this.labelOf = "of";
        }

        return LightboxOptions;

    })();

    Lightbox = (function() {

    function Lightbox(options) {
        this.options = options;
        this.album = [];
        this.currentImageIndex = void 0;
        this.img = img;
        this.number = number;
        this.position = position;
        this.init();
    }

    Lightbox.prototype.init = function() {
      //this.enable();
      return this.build();
    };

    Lightbox.prototype.enable = function() {
        var _this = this;
        return $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox]', function(e) {
            _this.start($(e.currentTarget));
            return false;
        });
    };

    Lightbox.prototype.build = function() {
        var $lightbox,
        _this = this;

        $("<div>", {
        id: 'lightboxOverlay'
        }).after($('<div/>', {
        id: 'lightbox'
        }).append($('<div/>', {
        "class": 'lb-outerContainer'
        }).append($('<div/>', {
        "class": 'lb-container'
        }).append($('<img/>', {
        "class": 'lb-image'
        }), $('<div/>', {
        "class": 'lb-nav'
        }).append($('<a/>', {
        "class": 'lb-prev'
        }), $('<a/>', {
        "class": 'lb-next'
        })), $('<div/>', {
        "class": 'lb-loader'
        }).append($('<a/>', {
        "class": 'lb-cancel'
        }).append($('<img/>', {
        src: this.options.fileLoadingImage
        }))))), $('<div/>', {
        "class": 'lb-dataContainer'
        }).append($('<div/>', {
        "class": 'lb-data'
        }).append($('<div/>', {
        "class": 'lb-details'
        }).append($('<span/>', {
        "class": 'lb-caption'
        }), $('<span/>', {
        "class": 'lb-number'
        })), $('<div/>', {
        "class": 'lb-closeContainer'
        }).append($('<a/>', {
        "class": 'lb-close'
        }).append($('<img/>', {
        src: this.options.fileCloseImage
        }))))))).appendTo($('body'));

        $('#lightboxOverlay').hide().on('click', function(e) {
            _this.end();
            return false;
        });

        $lightbox = $('#lightbox');

        $lightbox.hide().on('click', function(e) {
            if ($(e.target).attr('id') === 'lightbox') _this.end();
            return false;
        });

        $lightbox.find('.lb-outerContainer').on('click', function(e) {
            if ($(e.target).attr('id') === 'lightbox') _this.end();
            return false;
        });

        $lightbox.find('.lb-prev').on('click', function(e) {
            _this.changeImage(_this.currentImageIndex - 1);
            return false;
        });

        $lightbox.find('.lb-next').on('click', function(e) {
            _this.changeImage(_this.currentImageIndex + 1);
            return false;
        });

        $lightbox.find('.lb-loader, .lb-close').on('click', function(e) {
            _this.end();
            return false;
        });
    };

    //Lightbox.prototype.start = function($link) {
    Lightbox.prototype.start = function() {
      var $lightbox, $window, a, i, imageNumber, left, top, _len, _ref;
      $(window).on("resize", this.sizeOverlay);
      $('select, object, embed').css({
        visibility: "hidden"
      });
      $('#lightboxOverlay').width($(document).width()).height($(document).height()).fadeIn(this.options.fadeDuration);
      this.album = [];
      imageNumber = 0;
      this.album.push({
        link: img,
        title: "taken at 8 juli 2013"
      });
      //$('#peekview').html("kampret").fadeIn(500,0.8);
      //console.log(img);
      //alert(img);
      /*
      if ($link.attr('rel') === 'lightbox') {
        this.album.push({
          link: $link.attr('href'),
          title: $link.attr('title')
        });
      } else {
        _ref = $($link.prop("tagName") + '[rel="' + $link.attr('rel') + '"]');
        for (i = 0, _len = _ref.length; i < _len; i++) {
          a = _ref[i];
          this.album.push({
            link: $(a).attr('href'),
            title: $(a).attr('title')
          });
          if ($(a).attr('href') === $link.attr('href')) imageNumber = i;
        }
      }
      */
      $window = $(window);
      top = $window.scrollTop() + $window.height() / 10;
      left = $window.scrollLeft();
      $lightbox = $('#lightbox');
      $lightbox.css({
        top: top + 'px',
        left: left + 'px'
      }).fadeIn(this.options.fadeDuration);
      this.changeImage(imageNumber);
    };

    Lightbox.prototype.changeImage = function(imageNumber) {
      var $image, $lightbox, preloader,
        _this = this;
      this.disableKeyboardNav();
      $lightbox = $('#lightbox');
      $image = $lightbox.find('.lb-image');
      this.sizeOverlay();
      $('#lightboxOverlay').fadeIn(this.options.fadeDuration);
      $('.loader').fadeIn('slow');
      $lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
      $lightbox.find('.lb-outerContainer').addClass('animating');
      preloader = new Image;
      preloader.onload = function() {
        $image.attr('src', _this.album[imageNumber].link);
        $image.width = preloader.width;
        $image.height = preloader.height;
        return _this.sizeContainer(preloader.width, preloader.height);
      };
      preloader.src = this.album[imageNumber].link;
      this.currentImageIndex = imageNumber;
    };

    Lightbox.prototype.sizeOverlay = function() {
      return $('#lightboxOverlay').width($(document).width()).height($(document).height());
    };

    Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
      var $container, $lightbox, $outerContainer, containerBottomPadding, containerLeftPadding, containerRightPadding, containerTopPadding, newHeight, newWidth, oldHeight, oldWidth,
        _this = this;
      $lightbox = $('#lightbox');
      $outerContainer = $lightbox.find('.lb-outerContainer');
      oldWidth = $outerContainer.outerWidth();
      oldHeight = $outerContainer.outerHeight();
      $container = $lightbox.find('.lb-container');
      containerTopPadding = parseInt($container.css('padding-top'), 10);
      containerRightPadding = parseInt($container.css('padding-right'), 10);
      containerBottomPadding = parseInt($container.css('padding-bottom'), 10);
      containerLeftPadding = parseInt($container.css('padding-left'), 10);
      newWidth = imageWidth + containerLeftPadding + containerRightPadding;
      newHeight = imageHeight + containerTopPadding + containerBottomPadding;
      if (newWidth !== oldWidth && newHeight !== oldHeight) {
        $outerContainer.animate({
          width: newWidth,
          height: newHeight
        }, this.options.resizeDuration, 'swing');
      } else if (newWidth !== oldWidth) {
        $outerContainer.animate({
          width: newWidth
        }, this.options.resizeDuration, 'swing');
      } else if (newHeight !== oldHeight) {
        $outerContainer.animate({
          height: newHeight
        }, this.options.resizeDuration, 'swing');
      }
      setTimeout(function() {
        $lightbox.find('.lb-dataContainer').width(newWidth);
        $lightbox.find('.lb-prevLink').height(newHeight);
        $lightbox.find('.lb-nextLink').height(newHeight);
        _this.showImage();
      }, this.options.resizeDuration);
    };

    Lightbox.prototype.showImage = function() {
      var $lightbox;
      $lightbox = $('#lightbox');
      $lightbox.find('.lb-loader').hide();
      $lightbox.find('.lb-image').fadeIn('slow');
      this.updateNav();
      this.updateDetails();
      this.preloadNeighboringImages();
      this.enableKeyboardNav();
    };

    Lightbox.prototype.updateNav = function() {
      var $lightbox;
      $lightbox = $('#lightbox');
      $lightbox.find('.lb-nav').show();
      if (this.currentImageIndex > 0) $lightbox.find('.lb-prev').show();
      if (this.currentImageIndex < this.album.length - 1) {
        $lightbox.find('.lb-next').show();
      }
    };

    Lightbox.prototype.updateDetails = function() {
      var $lightbox,
        _this = this;
      $lightbox = $('#lightbox');
      if (typeof this.album[this.currentImageIndex].title !== 'undefined' && this.album[this.currentImageIndex].title !== "") {
        $lightbox.find('.lb-caption').html(this.album[this.currentImageIndex].title).fadeIn('fast');
      }
      if (this.album.length > 1) {
        $lightbox.find('.lb-number').html(this.options.labelImage + ' ' + (this.currentImageIndex + 1) + ' ' + this.options.labelOf + '  ' + this.album.length).fadeIn('fast');
      } else {
        $lightbox.find('.lb-number').hide();
      }
      $lightbox.find('.lb-outerContainer').removeClass('animating');
      $lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration, function() {
        return _this.sizeOverlay();
      });
    };

    Lightbox.prototype.preloadNeighboringImages = function() {
      var preloadNext, preloadPrev;
      if (this.album.length > this.currentImageIndex + 1) {
        preloadNext = new Image;
        preloadNext.src = this.album[this.currentImageIndex + 1].link;
      }
      if (this.currentImageIndex > 0) {
        preloadPrev = new Image;
        preloadPrev.src = this.album[this.currentImageIndex - 1].link;
      }
    };

    Lightbox.prototype.enableKeyboardNav = function() {
      $(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
    };

    Lightbox.prototype.disableKeyboardNav = function() {
      $(document).off('.keyboard');
    };

    Lightbox.prototype.keyboardAction = function(event) {
      var KEYCODE_ESC, KEYCODE_LEFTARROW, KEYCODE_RIGHTARROW, key, keycode;
      KEYCODE_ESC = 27;
      KEYCODE_LEFTARROW = 37;
      KEYCODE_RIGHTARROW = 39;
      keycode = event.keyCode;
      key = String.fromCharCode(keycode).toLowerCase();
      if (keycode === KEYCODE_ESC || key.match(/x|o|c|e/)) {
        this.end();
      } else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
        if (this.currentImageIndex !== 0) {
          this.changeImage(this.currentImageIndex - 1);
        }
      } else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
        if (this.currentImageIndex !== this.album.length - 1) {
          this.changeImage(this.currentImageIndex + 1);
        }
      }
    };

    Lightbox.prototype.end = function() {
      this.disableKeyboardNav();
      $(window).off("resize", this.sizeOverlay);
      $('#lightbox').fadeOut(this.options.fadeDuration);
      $('#lightboxOverlay').fadeOut(this.options.fadeDuration);
      return $('select, object, embed').css({
        visibility: "visible"
      });
    };

    return Lightbox;

    })();

    var lightbox, options;
    options = new LightboxOptions;
    lightbox = new Lightbox(options);
    lightbox.start();

    return false;
}

/**
 * Renders any Vsign Grids that are detected
 * @param {Object} gridId
 */
function VsignGridRender(gridId){

    // Grid ID tells us which grid we need to render
    var gridDiv 	= '#' + gridId;
    var filter 		= $('#' + gridId + ' .VsignFilter form');
    var outputDiv 	= $('#' + gridId + ' .VsignData ');

    // AJAX call to get the VsignData
    $.ajax({
        type: "post",
        url: "index.php?ajax=true",
        dataType: "json",
        data: filter.formSerialize(),
        success: function(response){

            var respHtml;

            if (response.success) {
                respHtml = response.html;
            }
            else {
                // Login Form needed?
                if (response.login) {
                    LoginBox(response.message);
                    return false;
                }
                else {
                    // Just an error we dont know about
                    respHtml = response.message;
                }
            }

            $(outputDiv).html(respHtml);

            // Do we need to do anything else now?
            if (response.sortable) {
                // Call paging
                var sortingDiv = response.sortingDiv;

                if ($('tbody', sortingDiv).html() != "") {
                    $(sortingDiv).tablesorter({
                        sortList: [[0, 0]],
                        widthFixed: true
                    })
                }
            }

            // Do we have to call any functions due to this success?
            if (response.callBack != "" && response.callBack != undefined) {
                eval(response.callBack)(name);
            }

            // Call VsignInitialise for this form
            VsignInitialise(gridDiv);

            // Make some buttons
            $('button', outputDiv).button();

            return false;
        }
    });

    //so that we dont submit forms
    return false;
}

/**
 * Renders the formid provided
 * @param {String} formUrl
 */
function VsignFormRender(formUrl) {

    // Prepare the Dialog
    $('#div_dialog').dialog('destroy');
    $('#div_dialog').html("");

    // Call with AJAX
    $.ajax({
        type: "get",
        url: formUrl + "&ajax=true",
        cache: false,
        dataType: "json",
        success: function(response){

            // Was the Call successful
            if (response.success) {

                // Set the dialog HTML to be the response HTML
                $('#div_dialog').html(response.html);

                var dialogTitle = "VSign";
                var dialogWidth = "500";
                var dialogHeight = "500";

                // Is there a title for the dialog?
                if (response.dialogTitle != undefined && response.dialogTitle != "") {
                    // Set the dialog title
                    dialogTitle =  response.dialogTitle;
                }

                // Do we need to alter the dialog size?
                if (response.dialogSize) {
                    dialogWidth 	= response.dialogWidth;
                    dialogHeight	= response.dialogHeight;
                }

                // Buttons?
                var buttons = '';

                if (response.buttons != '') {
                    $.each(
                        response.buttons,
                        function(index, value) {
                            var extrabutton = {};
                            extrabutton[index] = function(){
                                eval(value);
                            }

                            buttons = $.extend(buttons, extrabutton);
                        }
                        );
                }

                // Create the dialog with our parameters
                $('#div_dialog').dialog({
                    title: dialogTitle,
                    width: dialogWidth,
                    height: dialogHeight,
                    draggable: true,
                    resizable: false,
                    bgiframe: true,
                    autoOpen: true,
                    buttons: buttons
                });

                // Do we have to call any functions due to this success?
                if (response.callBack != "" && response.callBack != undefined) {
                    eval(response.callBack)(name);
                }

                // Focus in the first form element
                if (response.focusInFirstInput) {
                    $('input[type=text]', '#div_dialog').eq(0).focus();
                }

                if (response.appendHiddenSubmit) {
                    if ($("input[type=submit]", "#div_dialog").length == 0) {
                        $("form", "#div_dialog").append('<input type="submit" style="display:none" />');
                    }
                }

                // Do we need to do anything else now?
                if (response.sortable) {
                    // Call paging
                    if ($(response.sortingDiv + ' tbody', '#div_dialog').html() != "") {
                        $(response.sortingDiv, '#div_dialog').tablesorter({
                            sortList: [[0, 0]],
                            widthFixed: true
                        })
                    }
                }

                // Call Vsign Init for this form
                VsignInitialise("#div_dialog");
            }
            else {
                // Login Form needed?
                if (response.login) {
                    LoginBox(response.message);

                    return false;
                }
                else {
                    // Just an error we dont know about
                    if (response.message == undefined) {
                        SystemMessage(response);
                    }
                    else {
                        SystemMessage(response.message);
                    }
                }
            }

            return false;
        }
    });

    // Dont then submit the link/button
    return false;
}

/**
 * Vsign Ping
 * @param {String} url
 */
function VsignPing(url) {

    // Call with AJAX
    $.ajax({
        type: "get",
        url: url + "&ajax=true",
        cache: false,
        dataType: "json",
        success: function(response){

            // Was the Call successful
            if (!response.success) {
                // Login Form needed?
                if (response.login) {
                    $('#div_dialog').dialog('destroy');

                    LoginBox(response.message);
                    
                    return false;
                }

                if (response.clockUpdate) {
                    VsignClockUpdate(response.html);
                }
            }

            return false;
        }
    });

    // Dont then submit the link/button
    return false;
}

/**
 * Updates the Clock with the latest time
 * @param {Object} time
 */
function VsignClockUpdate(time)
{
    $('#VsignClock').html(time);

    return;
}

/**
 * Submits the Form
 * @param {Object} form
 */
function VsignFormSubmit(form) {
    // Get the URL from the action part of the form)
    var url = $(form).attr("action") + "&ajax=true";

    $.ajax({
        type:"post",
        url:url,
        cache:false,
        dataType:"json",
        data:$(form).serialize(),
        success: VsignSubmitResponse
    });

    return;
}

/**
 * Handles the submit response from an AJAX call
 * @param {Object} response
 */
function VsignSubmitResponse(response) {
    // Did we actually succeed
    if (response.success) {
        // Success - what do we do now?

        // We might need to keep the form open
        if (!response.keepOpen) {
            $('#div_dialog').dialog("close");
        }

        // Should we display the message?
        if (!response.hideMessage) {
            if (response.message != '')
                SystemMessage(response.message, true);
        }

        // Do we need to fire a callback function?
        if (response.callBack != null && response.callBack != "") {
            eval(response.callBack)(name);
        }

        // Do we need to load a new form?
        if (response.loadForm) {
            // We need: uri, callback, onsubmit
            var uri = response.loadFormUri;

            // File forms give the URI back with &amp's in it
            uri = unescape(uri);

            VsignFormRender(uri);
        }

        // Should we refresh the window or refresh the Grids?
        if (response.refresh) {
            // We need to refresh - check to see if there is a new location provided
            if (response.refreshLocation == undefined || response.refreshLocation == "") {
                // If not refresh the current location
                window.location.reload();
            }
            else {
                // Refresh to the new location
                window.location = response.refreshLocation;
            }
        }
        else {
            // We should refresh the grids (this is a global refresh)
            $(" .VsignGrid").each(function(){

                var gridId = $(this).attr("id");

                // Render
                VsignGridRender(gridId);
            });
        }
    }
    else {
        // Why did we fail?
        if (response.login) {
            // We were logged out
            LoginBox(response.message);
            return false;
        }
        else {
            // Likely just an error that we want to report on
            SystemMessage(response.message, false);
        }
    }

    return false;
}

/**
 * Renders the formid provided
 * @param {String} formId
 */
function VsignHelpRender(formUrl) {

    // Prepare the Dialog
    $('#help_dialog').dialog("destroy");
    $('#help_dialog').html("");

    // Call with AJAX
    $.ajax({
        type: "get",
        url: formUrl + "&ajax=true",
        cache: false,
        dataType: "json",
        success: function(response){

            // Was the Call successful
            if (response.success) {
                // Set the dialog HTML to be the response HTML
                $('#help_dialog').html(response.html);

                var dialogTitle = "VSign Digital Signage Help";
                var dialogWidth = "500";
                var dialogHeight = "500";

                // Is there a title for the dialog?
                if (response.dialogTitle != undefined && response.dialogTitle != "") {
                    // Set the dialog title
                    dialogTitle =  response.dialogTitle;
                }

                // Do we need to alter the dialog size?
                if (response.dialogSize) {
                    dialogWidth 	= response.dialogWidth;
                    dialogHeight	= response.dialogHeight;
                }

                // Buttons?
                var buttons = '';

                if (response.buttons != '') {
                    $.each(
                        response.buttons,
                        function(index, value) {
                            var extrabutton = {};
                            extrabutton[index] = function(){
                                eval(value);
                            }

                            buttons 		= $.extend(buttons, extrabutton);
                        }
                        );
                }

                // Create the dialog with our parameters
                $('#help_dialog').dialog({
                    title: dialogTitle,
                    width: dialogWidth,
                    height: dialogHeight,
                    draggable: true,
                    resizable: false,
                    bgiframe: true,
                    autoOpen: true,
                    buttons: buttons
                });

                // Do we have to call any functions due to this success?
                if (response.callBack != "" && response.callBack != undefined) {
                    eval(response.callBack)(name);
                }

                // Focus in the first form element
                $('input[@type=text]', '#help_dialog').eq(0).focus();

                // Call Vsign Init for this form
                VsignInitialise("#help_dialog");
            }
            else {
                // Login Form needed?
                if (response.login) {
                    LoginBox(response.message);
                    return false;
                }
                else {
                    // Just an error we dont know about
                    if (response.message == undefined) {
                        SystemMessage(response);
                    }
                    else {
                        SystemMessage(response.message);
                    }
                }
            }

            return false;
        }
    });

    // Dont then submit the link/button
    return false;
}

/**
 * Renders a Hover window and sets up events to destroy the window.
 */
function VsignHoverRender(url, x, y)
{
    // Call some AJAX
    // TODO: Change this to be hover code
    $.ajax({
        type: "get",
        url: url + "&ajax=true",
        cache: false,
        dataType: "json",
        success: function(response){

            // Was the Call successful
            if (response.success) {

                var dialogWidth = "500";
                var dialogHeight = "500";

                // Do we need to alter the dialog size?
                if (response.dialogSize) {
                    dialogWidth 	= response.dialogWidth;
                    dialogHeight	= response.dialogHeight;
                }

                // Create the the popup bubble with our parameters
                $("body").append("<div class=\"VsignHover\"></div>");

                $(".VsignHover").css("position", "absolute").css(
                {
                    display: "none",
                    width:dialogWidth,
                    height:dialogHeight,
                    top: y,
                    left: x
                }
                ).fadeIn("slow").hover(
                    function(){
                        return false
                    },
                    function(){
                        $(".VsignHover").hide().remove();
                        return false;
                    }
                    );

                // Set the dialog HTML to be the response HTML
                $('.VsignHover').html(response.html);

                // Do we have to call any functions due to this success?
                if (response.callBack != "" && response.callBack != undefined) {
                    eval(response.callBack)(name);
                }

                // Call Vsign Init for this form
                VsignInitialise(".VsignHover");

            }
            else {
                // Login Form needed?
                if (response.login) {
                    LoginBox(response.message);
                    return false;
                }
                else {
                    // Just an error we dont know about
                    if (response.message == undefined) {
                        SystemMessage(response);
                    }
                    else {
                        SystemMessage(response.message);
                    }
                }
            }

            return false;
        }
    });

    // Dont then submit the link/button
    return false;
}

/**
 * Closes the dialog window
 */
function VsignDialogClose() {
    $('#div_dialog').dialog('close');
}

function VsignSwapDialog(formUrl) {
    $('#div_dialog').dialog('close');
    VsignFormRender(formUrl);
}

/**
 * Display a login box
 * @param {String} message
 */
function LoginBox(message) {
    $('#div_dialog').html(message);

    //capture the form submit
    $('.VsignForm').submit(function() {
        VsignFormSubmit(this);
        return false;
    });

    // Create the dialog with our parameters
    $('#div_dialog').dialog({
        title: 'Please Login to Proceed',
        width: 300,
        height: 300,
        draggable: true,
        resizable: false,
        bgiframe: true,
        autoOpen: true,
        position: 'center',
        modal: true,
        buttons: {
            "Login": function(){
                VsignFormSubmit($('#VsignLoginForm').submit())
            }
            }
    });

    // Focus in the first form element
    $('input[type=text]', '#div_dialog').eq(0).focus();

    if ($("input[type=submit]", "#div_dialog").length == 0) {
        $("form", "#div_dialog").append('<input type="submit" style="display:none" />');
    }

    return;
}

/**
 * Displays the system message
 * @param {String} messageText
 * @param {Bool} success
 */
function SystemMessage(messageText, success) {

    if (messageText == '' || messageText == null) return;

    var message = $('#system_message');

    $('span', message).html(messageText);
    message.dialog('open');

    if (!success)
        return;

    // Close after 1 second
    setTimeout(function() {
            $('#system_message').dialog('close');
    }, 1000 );
}

/**
 * Toggles the FilterForm view
 */
function ToggleFilterView(div)
{
    if ($('#'+div).css("display") == "none") {
        $('#'+div).fadeIn("slow");
    }
    else {
        $('#'+div).fadeOut("slow");
    }

    return false;
}

/**
 * Switches an item between 2 connected lists.
 */
function switchLists(e) {
   // determine which list they are in
   // http://www.remotesynthesis.com/post.cfm/working-with-related-sortable-lists-in-jquery-ui
   var otherList = $($(e.currentTarget).parent().sortable("option","connectWith")).not($(e.currentTarget).parent());

   otherList.append(e.currentTarget);
}