/************************** JS Needed on Every Page*********************/

/**
 * @todo: Would it make more sense to another JS file to seperate from
 * the functions?
 */

$(document).ready(function() {


    /**
     * Call JS functions needed on every page
     */
     
    // Restrict pre-population of password fields
    //$('#loginPassword ').setAttribute( "autocomplete", "off" );
     
    // Determine browser and add a class to body element for browser-specific CSS
    var browsers = [
        { jQueryName: 'webkit', className: 'webkit' },
        { jQueryName: 'opera', className: 'webkit' },
        { jQueryName: 'msie', className: 'ie' },
        { jQueryName: 'mozilla', className: 'firefox' }
    ];
    
    for ( var i in browsers ) {
        if ( $.browser[ browsers[i].jQueryName ] ) {
            $('body').addClass( browsers[i].className );
        }
    }
    
    // Add major version number for ie
    if ( $.browser.msie ) {
        $('body').addClass( 'ie' + parseInt($.browser.version, 10) );
    }     
     
    // Turn off animation in IE6 an IE7
    if ( jQuery.browser.msie ) {
        jQuery.fx.off = true;
    }
    
    // Set up the region selector tooltip
    // @todo: Is this needed on every page?
    $('.tooltip-region-close').click(function() {
        $('.tooltip-region').toggle('fast');
        return false;
    });
    $('.change-region-label').click(function() {
        $('.tooltip-region').toggle('fast');
        return false;
    });
    
    $('.sprite-flag').click(function() {
        $('.tooltip-region').toggle('fast');
        return false;
    });
    
    
    /** Let's try to stick footer to the bottom **/
    $(function(){
    positionFooter();
    });
    
    function positionFooter(){
    var temp = 'result: '+$(document).height()+' - ' + $(window).height();
        if($(document).height() <= $(window).height()){
        //alert(temp);
        //$("#pwn-footer").css({position: "absolute",top:($(window).scrollTop()+$(window).height()-$("#pwn-footer").height())+"px"})
            
        }    
    }
 
    //$(window).scroll(positionFooter);
    $(window).resize(positionFooter)

    

});


/************************** JS Functions ******************************/

/**
 * Initialises the right menu tooltips (such as those on the homepage)
 * 
 * To create a new tooltip:
 * 
 * 1. Add the id of the actual tooltip div to the toolTips array.
 * 2. The link to open the tooltip must be the same as the tooltip id but
 *    with -link at the end.
 * 3. The close button (the cross on the actual tooltip) must be the name of
 *    the tooltip followed by -close
 * 4. Optionally, if the tooltip needs to be reset when it is re-opened (such as to
 *    hide a form submit) then add to the switch statement in
 *    rightMenuToolTips_ResetContent();
 *
 *
 * If you just need to open a right menu tooltip, use the
 * rightMenuToolTips_ShowTooltip(); function
 *
 */

var toolTips = Array('tooltip-international-dial-in-numbers', 'tooltip-in-conference-controls', 'tooltip-pin-reminder', 'tooltip-mobile-app','tooltip-schedule-call');

/**
 * Sets up the right menu tooltip (also know as 'informational links'), does the following:
 *  * Does some crazy hack to solve z index problems in IE
 *  * Sets up the tooltips
 *  * Checks if a specified url needs to open up a specific tab
 */
function rightMenuToolTips_Init() {

    // Fixes a z-index issues in IE7 an IE8.
    if ((jQuery.browser.version == '6.0')||(jQuery.browser.version == '7.0')) {
        rightIndexZindex = 1000;

        $('#right-menu-container li').each(function(index) {
        $(this).css('z-index',rightIndexZindex);
        rightIndexZindex = rightIndexZindex - 10;
        });
    }

    // Loop round each tooltip in our tooltip array to apply the onclick event
    // to the tooltip link and tooltip close buttons
    for (toolTipsIndex in toolTips) {

        // Attach click handler to the tooltip link
        $('#' + toolTips[toolTipsIndex] + '-link').click(function() {

            // Get the id of the tooltip being clicked by removing the "-link" from the current element id
            baseId = $(this).attr('id').replace('-link', '');

            // Open the tooltip
            rightMenuToolTips_ShowTooltip(baseId);
            return false;
        });

        // Attach the click handler to the tooltip close arrow
        $('#' + toolTips[toolTipsIndex] + '-close').click(function() {
            // Get the id of the tooltip being clicked by removing the "-close" from the current element id
            baseId = $(this).attr('id').replace('-close', '');
            // hide and reset tooltip
            $('#' + baseId).hide('fast');
            return false;
        });

    }

    /**
     * Certain urls need to open certain tabs or tooltips on page load, this goes all that
     */
    // get the page name without trailing slash
    pageString = location.pathname;
    pageString = pageString.replace(/\/$/, '');

    // Perform redirect
    switch(pageString) {
        case URL_IN_CONFERENCE_CONTROLS:
            rightMenuToolTips_ShowTooltip('tooltip-in-conference-controls');
            $('head').append('<link href="'+HOMEPAGE_CANONICAL_URL+'" rel="canonical" />');
            break;
        case URL_INTERNATIONAL_DIAL_IN_NUMBERS:
            rightMenuToolTips_ShowTooltip('tooltip-international-dial-in-numbers');
            $('head').append('<link href="'+HOMEPAGE_CANONICAL_URL+'" rel="canonical" />');
            break;
        case URL_PIN_REMINDER:
            rightMenuToolTips_ShowTooltip('tooltip-pin-reminder');
            $('head').append('<link href="'+HOMEPAGE_CANONICAL_URL+'" rel="canonical" />');
            break;
		case URL_MOBILE_APP:
            rightMenuToolTips_ShowTooltip('tooltip-mobile-app');
            $('head').append('<link href="'+HOMEPAGE_CANONICAL_URL+'" rel="canonical" />');
        break;
    }    

}

/**
 * Opens the specified tooltip, and closes the other tooltips on the right nav
 *
 * This is called by rightMenuToolTips_Init(); but can also be called manually
 * by passing the id of the tooltip to open:
 * e.g. rightMenuToolTips_ShowTooltip(tooltip-international-dial-in-numbers);
 *
 */
function rightMenuToolTips_ShowTooltip(toolTipId) {

    // If we are opening an element then hide any other open tooltip
    if ($('#' + toolTipId).is(':hidden')) {
        for (toolTiptoCloseIndex in toolTips) {
            if ($('#' + toolTips[toolTiptoCloseIndex]).is(':visible')) {
                $('#' + toolTips[toolTiptoCloseIndex]).hide('fast');
                rightMenuToolTips_ResetContent(toolTipId);
            }
        }
    }
    // If tooltip is hidden then reset its contents before showing
    if ($('#' + toolTipId).is(":hidden")) {
        rightMenuToolTips_ResetContent(toolTipId);
    }
    $('#' + toolTipId).toggle('fast');    
}

function showTimeInActionToolTips_Init() {
    $('.tooltip-showtime-in-action-close').click(function() {
        $('#tooltip-showtime-in-action').toggle('fast');
        return false;
    });
    $('.tooltip-showtime-in-action-link').click(function() {
        $('#tooltip-showtime-in-action').toggle('fast');
        return false;
    });
}

/*My PWN Tooltips Array*/
var myPWNtoolTips = Array('tooltip-header-all-pins', 'tooltip-header-all-tels');

/**
 * Opens the myPWN Header Popup Window for either the All Pins or All Tels Window
 */
function myPwnHeader_init() {
    
    //Go through the Tooltips in the Array to apply the onClick Events. -link and -close buttons are applied
    for (toolTipsIndex in myPWNtoolTips) {

        //-link Function
        $('.' + myPWNtoolTips[toolTipsIndex] + '-link').click(function() {

             //Get the Class of the original Tooltip, by removing the -link and additional classes
            baseId = $(this).attr('class').replace('-link', '');

            //Open the Tooltip
            myPwnHeader_ShowTooltip(baseId);
            
            return false;
        });

        //-close Function
        $('.' + myPWNtoolTips[toolTipsIndex] + '-close').click(function() {
            
            //Get the Class of the original Tooltip, by removing the -close and additional classes
            baseId = $(this).attr('class').replace('-close floatright sprite tooltip-close', '');

            //Hide and Reset the Tooltip
            $('.' + baseId).hide('fast');
            
            return false;
        });
    }
    
    //Update Popup Description for the Skype and Worldwide Class
    $('.worldwide').html(MYPWN_DIALINNUMBER_WORLDWIDE);
    $('.skype').html(MYPWN_DIALINNUMBER_SKYPE);
}

/**
 * Opens the specified tooltip, and closes the other tooltips on the right nav
 *
 * This is called by myPwnHeader_init(); but can also be called manually
 * by passing the id of the tooltip to open:
 * e.g. myPwnHeader_ShowTooltip(tooltip-international-dial-in-numbers);
 *
 */
function myPwnHeader_ShowTooltip(toolTipId) {
    // If we are opening an element then hide any other open tooltip
    if ($('.' + toolTipId).is(':hidden')) {
        for (toolTiptoCloseIndex in myPWNtoolTips) {
            if ($('.' + myPWNtoolTips[toolTiptoCloseIndex]).is(':visible')) {
                $('.' + myPWNtoolTips[toolTiptoCloseIndex]).hide('fast');
            }
        }
    }
    $('.' + toolTipId).toggle('fast');    
}


/**
 * The premium tab has a submenu (overview, testimonials etc), apply this
 * function to the onclick of all the links, passing the content number
 * to be loaded (rather than content name, as in theory this could change
 * via CMS). Also pass the link element so we can change its colour to
 * activated. It will also change the colour of all other links in the
 * list to the unselect colour
 */
function premiumLink(contentNumber, linkElement) {
    // Reset other link colours in the li
    // linkElement.parent().parent().children().removeClass('lightgreen');
    //linkElement.parent('li').children('a').removeClass('lightgreen');
    //alert(linkElement.parents('li').child('a').html());

    linkElement.parent().parent().find("li").each(function() {
        $(this).children('a').removeClass('selected');
    });

    // Remove all selected classes on links
    $('.submenu-premium li a').removeClass('selected');

    // Update link colour of selected tab
    linkElement.addClass('selected');
    if(typeof applyCufon == 'function') {
	applyCufon();
    }

    // Hide visible content, then show newly selected
    $('[id^=premium-content-]:visible').fadeOut('fast', function() {
        $('#premium-content-' + contentNumber).fadeIn('slow');
    });
    
    return false;
}

/**
 * Some tooltips need to be reset when they close, such as if the pin reminder
 * form has been submitted then the tooltip closed, when we reopen we 
 * no longer would wish to see the submit confirmation form
 */
function rightMenuToolTips_ResetContent(idTag) {
    switch(idTag) {
        case 'tooltip-pin-reminder':
            $('#pin-reminder-response-placeholder').hide();
            $('#pin-reminder-form-placeholder').show();
            break;
    }
}

/**
 * Resizes the specified image to the specified dimensions
 * 
 * If the image is not either at thumbWidth or largeWidth when the
 * function is called, it will resize the image to largeWidth and largeHeight
 * 
 * @param imageElement Jquery wrapped image element
 * @param thumbWidth   Small width of image
 * @param thumbHeight  Small height of image
 * @param largeWidth   Width of image at full size
 * @param largeHeight  Height of image at full size
 */
function resizeImageAnimated(imageElement, thumbWidth, thumbHeight, largeWidth, largeHeight) {
    if (imageElement.attr('width') == thumbWidth) {
        imageElement.animate({"width": largeWidth, "height": largeHeight}, "slow");
    } else {
        imageElement.animate({"width": thumbWidth, "height": thumbHeight}, "slow");
    }
}

/**
 * Cufon puts in the non web safe fonts when needed
 * 
 * This function gets applied on page load, but also needs to be re-run if content
 * gets dynamically loaded
 */
/*function applyCufon() {
    Cufon.replace('h1', {hover: true, fontFamily: 'Rockwell'});
    Cufon.replace('h2', {hover: true, fontFamily: 'Rockwell'});
    Cufon.replace('.rockwell', {hover: true, fontFamily: 'Rockwell'});
    Cufon.replace('.futura', {hover: true, fontFamily: 'Futura BdCn Bt'});
    Cufon.replace('button span', {hover: true, fontFamily: 'Rockwell'});
    Cufon.replace('button a', {hover: true, fontFamily: 'Rockwell'});
    Cufon.replace('.button a', {hover: true, fontFamily: 'Rockwell'});
    Cufon.replace('.nice-gradient', {color: '-linear-gradient(#FFFFFF, #cccccc)', textShadow: '#314045 0px -1px' });

            Cufon.replace('.shadow', {
                textShadow: '#fff -1px -1px, #333 1px 1px'
            });
}*/

/**
 * Fades in and out <li>'s of a <ul> in sequence, one <li> at a time.
 * To use, just apply a class of list-fading to the <ul>, and ensure
 * listFade(); runs on page load.
 * Note, this function hides all the <li>'s on page load and then
 * fades the first one in, so ensure all <li>'s are visible on page
 * load
 *
 */
function listFade() {    
    // Loop round all ul's with the list-fading class
    $('ul.list-fading').each(function(index) {
    
        // If there is only one <li> then just show it with no affects
        if ($(this).children('li').length == 1) {
            return true;
        }

        // See if it is the first time this function has been run by seeing
        // if all li's are visible
        if ($(this).children('li:visible').length == $(this).children('li').length && $(this).children('li').length != 1) {
            // First time function is run so hide all li's
            $(this).children('li').hide();
            // Show the first li
            $(this).children('li:first-child').fadeIn('slow');
        } else {
            // It is not the first time function has run, so we need to fade out the currently
            // visible li and then fade in the next, unless we have reached the end
            // of the list, then we need to show the first li again

            // Get the index of the next <li> to show
            nextLi = $(this).children('li:visible').index() + 2; // Add 2 as index() starts from 0
                                                                 // :nth-child() starts from 1
                                                                 
            // If we have reached the end of the list, the start from the first item
            if (nextLi > $(this).children().length) {
                nextLi = 1;
            }
            // Do the fading in and out
            $(this).children('li:visible').fadeOut('slow');
            $(this).children('li:nth-child(' + (nextLi) + ')').delay(900).fadeIn('slow');
        }
    });
    // Add time delay to run this function again to show the next list item
    setTimeout('listFade()', 9000); // To change the time delay between items you
                                    // only need to change here
}

/**
 * This loads the social media footer content from the cached JSON based HTML file
 * into the corresponding ul.
 *
 * To know which ul to load the data into, it calculates the ID tag by getting the
 * JSON key, then prepends socialMediaFooter_
 */
function socialMediaFooter_Init() {
    $.getJSON('/ajax/social-media-footer.php', function(data) {
        $.each(data, function(key, listItems) {
            $('#socialMediaFooter_' + key).html(listItems);
        });
    });
    // Starts the fading of the articles
    listFade();
}



/**
 * Sets up the fading of the promotional boxes. (The big images
 * on the lower right half of the home page, also appears on some other pages)
 *
 * They loop round once then stop on the first slide
 * If the slide is hovered then animation stops
 * There is also a navigation for these elements see function
 * for this promotionalFadeShowSlide()
 */
function promotionalFadeInitialise() {

    // Tracks which list item should be shown
    liToShow = 0;
    
    // Sets the duration each slide is shown for, only needs to be changed
    // here
    promotionalFadeSlideSpeed = 5000;

    // Add time delay to call function to show the next slide
    promotionalTimeout = setTimeout('promotionalFadeNext()', promotionalFadeSlideSpeed);

    // Set up cancelling of fade on hover of the promotionals area
    $('#rotating-promotional-container').mouseenter(function() {
        clearTimeout(promotionalTimeout);
    });

}

/**
 * Figures out what slide is the next one to show, then does the
 * function call do show it
 *
 * Stops on the first slide after one iteration
 */
function promotionalFadeNext() {

    //load first image of the slide
    if (liToShow == 0) {
        var slideUrl = $('ul#rotating-promotional-list li:eq(' + liToShow + ')').attr('title');
        $('ul#rotating-promotional-list li:eq(' + liToShow + ')').attr('title', '');
        if (slideUrl != '') {
            $('ul#rotating-promotional-list li:eq(' + liToShow + ')').css({'backgroundImage': 'url(' + slideUrl +')'});
        }    
    }

    liToShow = liToShow + 1;

    // Hide the visibile list item(s)
    $("ul#rotating-promotional-list").children('li:visible').hide();

    // See if we have reached the last slide, if so we need to show the first
    // one. Note we do not call setTimeout(); as we don't want animation to continue
    // after all slides have been shown
    if (liToShow >= ($("ul#rotating-promotional-list").children().length)) {
        // Show first slide and not show any more slides
        promotionalFadeShowSlide(0, true);
    } else {
        // Show next slide and call this function again to show next slide
        promotionalTimeout = setTimeout('promotionalFadeNext()', promotionalFadeSlideSpeed);
        promotionalFadeShowSlide(liToShow);
    }
}

/**
 * Show the specified slide and highlight the corresponding left nav
 *
 * @param slideNum      int         Slide number to show, 1 being the first slide
 * @param cancelLooping null|bool   If true, will stop the rotator automatically moving
 *                                  to the next slide
 */
function promotionalFadeShowSlide(slideNum, cancelLooping) {

    // Show specified left nav
    $('ul#rotating-promotional-links li').removeClass('filled');
    $('ul#rotating-promotional-links li:eq(' + slideNum + ')').addClass('filled');

    // Show specified slide
    $('ul#rotating-promotional-list li:visible').hide();
    var slideUrl = $('ul#rotating-promotional-list li:eq(' + slideNum + ')').attr('title');
    $('ul#rotating-promotional-list li:eq(' + slideNum + ')').attr('title', '');
    if (slideUrl != '') {
        $('ul#rotating-promotional-list li:eq(' + slideNum + ')').css({'backgroundImage': 'url(' + slideUrl +')'});
    }
    $('ul#rotating-promotional-list li:eq(' + slideNum + ')').show();

    // If cancelLooping was set to true, then clear the timeout which shows the next slide
    if (cancelLooping !== undefined && cancelLooping) {
        clearTimeout(promotionalTimeout);
    }

}

/**
 * TOGGLE LIST
 *
 * The FAQ page has a show/hide component which has a links at the top,
 * which when clicked show the corresponding content.
 * 
 * To set this up, put the main content which needs to be toggled in
 * <ul> list items, ensuring that all content which should be hidden on page load
 * is hidden via css. Also give that <ul> a nice id, like faq_show_hide_list.
 *
 * Then to show the content for a particular li, pass its index and the 
 * id of the list, it will show the required li and hide the rest:
 *
 * Eg:
 *   <a href="#" onclick="toggleListItems_ShowListItem(1, 'faq_show_hide_list');">link 1</a>
 *
 * Will show the content of the first li in a ul with id of 'faq_show_hide_list'
 */
function toggleList_ShowListItem(itemNumber, listId) {
    $('#' + listId).children('li:visible').hide();
    $('#' + listId).children('li:nth-child(' + (itemNumber) + ')').fadeIn('fast');
}


/**
 * MENU DROPDOWNS
 * shows dropdown menu on main top menu (header)
 */
 

function hide_Submenu2(obj) {
    obj.children("div").hide('slow');
    obj.removeClass("active");
}

/**
 * Sets up the drop down menus for the horizontal navigation bar near the
 * top of the page
 */
function dropDownMenu_Init() {

    // Chrome is not too good with using show at a speed,
    // so disable it on a per browser basis
    if ($.browser.safari || $.browser.webkit) {
        showHideSpeed = null;
    } else {
        showHideSpeed = 'fast';
    }
     
    $('#top-menu2 > li').mouseenter(function() {
        $(this).addClass('active');
        $('div',this).show(showHideSpeed);
    });
    
    $('#top-menu1 > li').mouseenter(function() {
        $(this).addClass('active');
        $('div',this).show(showHideSpeed);
    });
    
    $('#top-menu2 > li').mouseleave(function() {
        obj = $(this);
        obj.removeClass("active");
        obj.children("div").hide(showHideSpeed);
    });
    
    $('#top-menu1 > li').mouseleave(function() {
        obj = $(this);
        obj.removeClass("active");
        obj.children("div").hide(showHideSpeed);
    });
    
    $('.top-submenu-container').mouseenter(function() {
        clearTimeout(menuTimeOut);
    });

    /* border around input */
    $(':input')
     .not(':button, :submit, :reset, :hidden, .no-hightlight')
     .focus(function () { $(this).parent('span').removeClass('mypwn-input-container').addClass('mypwn-input-container-focused') });

    $(':input')
     .not(':button, :submit, :reset, :hidden, .no-hightlight')
     .blur(function () { $(this).parent('span').removeClass('mypwn-input-container-focused').addClass('mypwn-input-container') });
}

function videos_Init() {

    // Load extra libraries necessary for video carousel    
    $('<script type="text/javascript" src="/js/library/jquery.jcarousel.min.js">').appendTo('head');
    $('<script type="text/javascript" src="/js/library/jquery.polaroid.js">').appendTo('head');
    $('<script type="text/javascript" src="/js/library/jquery.prettyPhoto.js">').appendTo('head');
    $('head').append('<link rel="stylesheet" href="/css/library/jquery.prettyPhoto.css" type="text/css" />');
    $('head').append('<link rel="stylesheet" href="/css/library/jquery.jcarousel.css" type="text/css" />');

    $('#videos').jcarousel( { visible: 3, scroll: 3 } );
    
    $('#videos a').prettyPhoto({
        flash_markup:
            '<object id="flowplayer" width="{width}" height="{height}" data="{path}" type="application/x-shockwave-flash">' +
                '<param name="movie" value="{path}" />' +
                '<param name="allowfullscreen" value="true" />' +
                '<param value="opaque" name="wmode" />' +
            '</object>',
		callback: function(){ alert('track it')}
    });
        
    $('#videos .polaroid').polaroid({
        /*cufon: true,*/
        zoom: 1.6,
        preAnimate: function() {
            $('a', this).prettyPhoto();
            /*Cufon.replace('#polaroidOverlay h3', {hover: true, fontFamily: 'Rockwell'});*/
        }
    });
}

function chapterSelect_Init() {
    var $chapterSelectArea = $('#video-chapters, #video-chapter-select p, #video-chapter-select .arrow');
    var $arrow = $('#video-chapter-select .arrow');
    
    // Set up event handlers for extending & retracting the chapter select bar
    $chapterSelectArea
        .hover( function() {    // Mouseenter
            // Change arrow to lighter colour
            var height = $arrow.height();
            $arrow.css('background-position', '0 -'+height+'px');
            
            // Clear timeout for retracting chapter select bar, if set
            if ( $('#video-chapter-select').data('retractTimeout') != 'undefined' ) {
                window.clearTimeout( $('#video-chapter-select').data('retractTimeout') );
            }
        }, function() {            // Mouseleave
            // Return arrow to default colour
            $arrow.css('background-position', '');
            
            // Retract chapter select bar if mouse is outside of it for 500ms
            $('#video-chapter-select').data(
                'retractTimeout',
                window.setTimeout( function() { retractVideoChapterSelect() }, 500 ) 
            );
        }).click( function() {
            toggleVideoChapterSelect();
        });
        
    
    // Set up flowplayer    
    var videoUrl = $('#flowplayer').attr('href');
    $f('flowplayer', {
        src: '/flash/flowplayer-3.2.5.swf',
        wmode: 'opaque'
    },  {
        clip: {
            autoPlay: false,
            autoBuffering: true,
            baseUrl: videoUrl
        },
        
        plugins: {
            controls: {
                url: 'flowplayer.controls.swf'
            }
        }
    });


    // To prevent Firefox automatic drag & drop
    if ($.browser.mozilla) {
        $('#flowplayer').mousedown( function( event ) {
            event.preventDefault();
        });
    }
        
    // Set up click handlers for chapters (time index in seconds is in href of link, e.g. href="#30")
    $('#video-chapters a').click( function( event ) {
        event.preventDefault();
        $f().play().seek( $(this).attr('href').substring(1) );
    });
}

function extendVideoChapterSelect() {
    $('#video-chapter-select ul').removeClass('hidden');
    $('#video-chapters').animate({
        'width': '412'
    }, 'fast', function() {
        $('#video-chapter-select').data('extended', true);
    });
}

function retractVideoChapterSelect() {
    $('#video-chapters').animate({
        'width': '23'
    }, 'fast', function() {
        $('#video-chapter-select ul').addClass('hidden');
        $('#video-chapter-select').data('extended', false);
    });
}

function toggleVideoChapterSelect() {
    if ( $('#video-chapter-select').data('extended') ) {
        retractVideoChapterSelect();
    } else {
        extendVideoChapterSelect();
    }
}

/**
 * Shows a nice looking alert box.
 * 
 * An empty div with an id of dialog must be present on each page as the
 * alert box:
 * <div id="dialog"></div>
 * 
 * @param mainText  string
 * @param titleText string
 */
function dialogBox(mainText, titleText) {

    $( "#dialog" ).dialog({
        autoOpen: false,
        /* buttons: {close: function() {$( this ).dialog( "close" );}},*/
        show: {effect: "drop", duration: 300},
        hide: {effect: "drop", duration: 150},
        title: titleText
    });

    $('#dialog').html(mainText);
    $( "#dialog" ).dialog('open');

    return false;
}

/**
 * Initialises the displaying of the paginated news
 */
function newsPagination_init() {
    newsPagination_LoadPaginatedPage(0, 5);
}

/**
 * Loads up the list of pagianted news articles for the specified page based on the
 * quantity per page, and places them in an div with id of news_paginator_placeholder:
 * Note the page number in this function start from 0, but obviously we wouldn't show
 * that to a user
 * newsPagination_LoadPaginatedPage(0, 10);
 * 
 * This also updates the value of all elements with a class of items_per_page to
 * be that of articlesPerPage
 
 * Specify -1 as the quantity per page to view all articles, eg:
 * newsPagination_LoadPaginatedPage(0, -1);
 *
 * @param int pageNumber       The page paginated page number to display, starting from 0
 * @param int articlesPerPage  Number of articles to show on each page, -1 for all articles
 */
function newsPagination_LoadPaginatedPage(pageNumber, articlesPerPage) {

    // Change the value of the items_per_page select box to be that of pageNumber
    $("select[name=items_per_page]").val(articlesPerPage);
    
    // Perform request to get news articles
    $.get('/News/ajax/paginator.php', {'pageNumber': pageNumber, 'articlesPerPage': articlesPerPage}, function(responseText) {
        reponseArr = eval('(' + responseText + ')');
        $('#pager').html(reponseArr['navigation']);
        $('#news-list').html(reponseArr['articles']);
    });
}

/**
 * Google Tracker functions
 */
function Google_tracker(page_name)
{
    setTimeout("Google_track('"+page_name+"')", 1000);        //delay to wait the footer to load: the footer initializes Google analytics
}

function Google_track(page_name)
{
    try{    
            _gaq.push(['_trackPageview', page_name]);
            //pageTracker._trackPageview(page_name);
    }
    catch(e){
            // console.log("GA code is not working :(");
    }
}

/**
 * Sets up relevant cookies to set a usr as logged in
 *
 * You may also be interested in the changeLoggedInBoxState(); function
 * to change the log in box at the top right of the page
 *
 * @param firstName string|null First name of user being logged in
 */
function logUserIn(firstName) {

    $.cookie('mypwn_login', 1);

    if (firstName !== undefined) {
        $.cookie('mypwn_login_firstname', firstName);
    }
}

/**
 * Removes cookies which mark a user as logged in
 *
 * You may also be interested in the changeLoggedInBoxState(); function
 * to change the log in box at the top right of the page
 */
function logUserOut() {
    $.cookie('mypwn_login', 0);
}

/**
 * Initial How Conference Calling Works Page
 * 
 * Sets the video Player up.
 */
function howConfCallingWorks_Init() {
    $(document).ready(function() {
        if (videoLoaded == 'no') {
            $f("a.videoPlayer", "/flash/flowplayer-3.2.7.swf", {
                clip:{ autoPlay: true, autoBuffering: true }
            });
            videoLoaded = 'yes';
        }
    });
}

/**
 * Initial Setup of the Promotion Video Rotator
 * 
 * Currently used for the About-Us/Testimonials page
 */
function aboutUsTestimonials_Init(itemFallbackDimensionWidth) {
    //Append to Document Head
    $('<script type="text/javascript" src="/js/library/flowplayer-3.2.6.min.js"/>').appendTo('head');
    $('head').append('<link rel="stylesheet" href="/css/library/jquery.jcarousel.tango.css" type="text/css" />');
    
    $('#mycarousel').jcarousel({
        scroll: 1, //Scroll 1 Item at a Time
        auto: 5, //Time (seconds) It stays on each Item
        visible: 1, //How many Items to show at any given time
        wrap: 'both', //Wrap around on both sides of the list
        animation: 'slow', //The Animation between each Item
        itemFallbackDimension: itemFallbackDimensionWidth, //This is the IE Callback to fix the Clip Width
        initCallback: mycarousel_initCallback
    });    

    /*
    Flowplayer Start  - carousel.stopAuto();
    Flowplayer Pause  - carousel.startAuto(0);
    Flowplayer Resume - carousel.stopAuto();
    Flowplayer Finish - carousel.startAuto(0);
    */

    //FlowPlayer Video Configuration including jCarousel Functionality
    $f("a.videoPlayer", "/flash/flowplayer-3.2.7.swf", {
        clip:{ autoPlay: true, autoBuffering: true },
        
        //Start of Video, Stop the Carousel
        onStart: function() {
            var carousel = $('#mycarousel').data('jcarousel');
            carousel.stopAuto();
        },
        
        //When Pausing the Video, Start the Carousel
        onPause: function() {
            var carousel = $('#mycarousel').data('jcarousel');
            carousel.startAuto();
        },
        
        //When Resuming a Paused Video, Stop the Carousel
        onResume: function() {
            var carousel = $('#mycarousel').data('jcarousel');
            carousel.stopAuto();
        },
        
        //When Video has finished, and is showing the "Play again" button, Start the Carousel
        onFinish: function() {
            var carousel = $('#mycarousel').data('jcarousel');
            carousel.startAuto();    
        }
    });
}

/**
 * myCarousel Initial Callback Function
 */
function mycarousel_initCallback(carousel) {
    // Disable autoscrolling if the user clicks the next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
        $f("*").each(function() {
            if (this.isLoaded()) this.unload();
        });      
    });
    
    // Disable autoscrolling if the user clicks the prev button.
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
        $f("*").each(function() {
            if (this.isLoaded()) this.unload();
        });        
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        /*Another Check needs to be added here, to check if the current video is being played. It it is then do not start the Carousel, Else Start it*/
        var flowplayerPlayStatus = false;
        $f("*").each(function() {
            if (this.getState() == 3) flowplayerPlayStatus = true;
        });
        if (flowplayerPlayStatus !== false) {
            //Do Nothing
        }else{
            carousel.startAuto();
        }
    });
};

function SetCookie(name, value) {
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;

    //Generate the cookie string in "name=value" format
    var curCookie = name + "=" + value +
      ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
      ((path == null) ? "" : ("; path=" + path)) +
      ((domain == null) ? "" : ("; domain=" + domain)) +
      ((secure == true) ? "; secure" : "");

    // Saves Name Value pair in memory or text file 
    document.cookie = curCookie;
}

function GnrtExprDt(duration) {
    // duration = number of days cookie lives; expire immediately = -1; 
    var today = new Date();
    var expr = new Date();
    expr.setTime(today.getTime() + duration*24*60*60*1000);
    return  expr.toGMTString();
}

function StoreInfo(CkNm,val,ExpVlu) {
    var expd = new Date(GnrtExprDt(ExpVlu));
    SetCookie(CkNm, val, expd);
}

