$(document).ready(function roll_images(){
	var img = new Image();
	$('.rollover').each(function(){
		img.src = this.src.replace(/\.([a-z]+)$/, "_on.$1");
		img.src = this.src.replace(/\.([a-z]+)$/, "_click.$1");
	});

	$('.rollover').hover(function(){
		this.src = this.src.replace(/\.([a-z]+)$/, "_on.$1");
	},
	function() {
		this.src = this.src.replace(/_(on|click)?\.([a-z]+)$/, ".$2");
	});
	$('.rollover').mousedown(function(){
		this.src = this.src.replace(/_(on|click)?\.([a-z]+)$/, "_click.$2");
	});
	$('.rollover').mouseup(function(){
		this.src = this.src.replace(/_(on|click)?\.([a-z]+)$/, "_on.$2");
	});
	if (typeof(max_slider_pos) != "undefined" && typeof(current_summit_id) != "undefined" ) {
        //Removed on the 15/11/11 by Paul Brindle. This was called so many times that it was crashing all the sites. We need to
        //write a better script to replace this functionality, but for now it has been removed.
		//enable_summit_slider_rotation(1, current_summit_id);
	}
	if (typeof(max_partners_pos) != "undefined") {
		enable_rotate_partners(1);
	}
	
	/*
	$('#protected-password').keyup(function(e) {
		$('#protected-form-submit').focus();
	});
	*/
	
	$('#protected-password').keyup(function(e) {
      if(e.keyCode == 13) {
      	$('#protected-form-submit').click();
      }
	});
});

function video_testimonial(id)
{
	send_request(true, '/xmlhttp/video_testimonial.php?id='+id, 'videoPlayerPlaceholder');
}

/* GENERIC MODAL WINDOW FUNCTION */
function modal_window(url)
{
	send_request(true, url, 'modalwindow');
	$('#fade').slideDown(350,function() {
		$("#modalwindow").show();
	});
}

function hide_modal()
{
	$("#modalwindow").hide();
	$('#fade').slideUp(350);
}

/* PREVIOUS MAGAZINE ISSUES DROP DOWN */
function the_summit()
{
	var display = $('#the_summit').css("display");
	
	if(display == 'none')
	{
		$('#the_summit').slideDown(700);
		$('#the_summit_image').attr({ 
          src: "/assets/images/previous-summits-hide.png"
        });
	}
	else
	{
		$('#the_summit').slideUp(700);
		$('#the_summit_image').attr({ 
          src: "/assets/images/previous-summits-show.png"
        });
	}
}


/* Handle front page flash movie changing size... */
/* SetTimeout is used in case a more noticeable delay than 10ms needs to be added in future */
function moveFlashWindowUp() {
	setTimeout("$('#collapsible-player').animate({'height':'28px'}, 500)", 10);
}
	
function moveFlashWindowDown() {
	setTimeout("$('#collapsible-player').animate({'height':'310px'}, 500)", 10);
}


/* SUMMIT SLIDER */
function enable_summit_slider_rotation(current_slider_pos, summit_id)
{
	if ($('#summit-slider-a').height() > $('#summit-slider-container').height()) {
		$('#summit-slider-container').css({'height' : ($('#summit-slider-a').height() + 5)+'px'});
	}
	if(max_slider_pos > 1)
	{
		setTimeout("rotate_summit_slider("+current_slider_pos+", "+summit_id+", 'b')", 6000);
	}
}

function rotate_summit_slider(current_slider_pos, summit_id, sbox)
{
	// sbox is 'a' or 'b', depending on if we need to put stuff into
	// #summit-slider-a or #summit-slider-b.
	
	// Find out what the old/future sbox will be:
	sboxOld = sbox == 'a' ? 'b' : 'a';

	//$('#summit-slider-'+sboxOld).css({ 'zIndex' : '1' });	
	$('#summit-slider-'+sbox).css({'left' : '-230px'});	
	send_request(true, '/xmlhttp/summit_slider.php?pos='+current_slider_pos+'&id='+summit_id, 'summit-slider-'+sbox);

	
	$('#summit-slider-'+sbox).animate({'left': '0'}, {duration:1500});
	$('#summit-slider-'+sboxOld).animate({'left': '230px'}, {duration:1500});

	if ($('#summit-slider-'+sbox).height() > $('#summit-slider-container').height()) {
		// Make the container big enough to hold the slide... will make the page jump, but
		// at least this way it'll only jump on the first time through the slides...
		$('#summit-slider-container').css({'height' : ($('#summit-slider-'+sbox).height() + 5)+'px'});
	}
	
	if(current_slider_pos < max_slider_pos)
	{
		current_slider_pos += 1;
	}
	else
	{
		current_slider_pos = 0;
	}
	setTimeout("rotate_summit_slider("+current_slider_pos+", "+summit_id+", '"+sboxOld+"')", 6000);
}





/* PARTNERS ROTATION */
function enable_rotate_partners(current_partners_pos)
{
	setTimeout("rotate_partners("+current_partners_pos+")", 20000);
}

function rotate_partners(current_partners_pos)
{
	
	$('#partner-0').hide();
	$('#partner-1').hide();
	$('#partner-2').hide();
	$('#partner-3').hide();
	$('#partner-'+current_partners_pos).fadeIn(1000);
	
	if(current_partners_pos < max_partners_pos-1)
	{
		current_partners_pos += 1;
	}
	else
	{
		current_partners_pos = 0;
	}
	
	setTimeout("rotate_partners("+current_partners_pos+")", 20000);
}


/* BANNER ROTATION */
function enable_rotate_banner(hcurrent_banner_pos, package, id)
{
	setTimeout("rotate_banner("+hcurrent_banner_pos+", "+package+", '"+id+"')", 30000);
}

function rotate_banner(hcurrent_banner_pos, package, id)
{
	if(hcurrent_banner_pos < hmax_banner_pos-1)
	{
		hcurrent_banner_pos += 1;
	}
	else
	{
		hcurrent_banner_pos = 0;
	}
	
	send_request(true, '/xmlhttp/get_banner.php?package='+package+'&pos='+hcurrent_banner_pos, id);
	$('#'+id).fadeIn(300);
	setTimeout("rotate_banner("+hcurrent_banner_pos+", "+package+", '"+id+"')", 30000);
}


function fenable_rotate_banner(fcurrent_banner_pos, package, id)
{
	setTimeout("frotate_banner("+fcurrent_banner_pos+", "+package+", '"+id+"')", 30000);
}

function frotate_banner(fcurrent_banner_pos, package, id)
{
	if(fcurrent_banner_pos < fmax_banner_pos-1)
	{
		fcurrent_banner_pos += 1;
	}
	else
	{
		fcurrent_banner_pos = 0;
	}
	
	send_request(true, '/xmlhttp/get_banner.php?package='+package+'&pos='+fcurrent_banner_pos, id);
	$('#'+id).fadeIn(300);
	setTimeout("frotate_banner("+fcurrent_banner_pos+", "+package+", '"+id+"')", 30000);
}


/* SITE WIDE FUNCTIONS BELOW */
function reset_value(object, id)
{
	return object.value = '';
}

function set_value(id, value)
{
	return document.getElementById(id).value = value;
}

function hide_element(id)
{
	$('#'+id).hide();
}

function show_element(id)
{
	$('#'+id).show();
}

function get_value(id)
{
	return document.getElementById(id).value;
}

function get_selected_value(objid)
{
	return objid.options[objid.selectedIndex].value;
}

function other_element(theobject, theid, othervalue)
{
	if(get_selected_value(theobject) == othervalue)
	{
		show_element(theid);
	}
	else
	{
		hide_element(theid);
	}
}

function send_to_friend(the_title, the_link)
{
	var name = get_value('name');
	var email = get_value('email');
	var note = get_value('unote');
	modal_window('/xmlhttp/send_to_friend.php?title='+the_title+'&link='+the_link+'&name='+name+'&email='+email+'&note='+note);
}


function MM_preloadImages() { //v3.0
  var d=document;if(d.images){if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){d.MM_p[j]=new Image;d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;document.MM_sr=new Array;for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;if(!x.oSrc) x.oSrc=x.src;x.src=a[i+2];}
}

//Tab controls for the program and advisory-programme pages
$(document).ready(function()
{
    $('.days .tab').click(function()
    {
        //Retrieve the ID
        var id = $(this).attr('id');
        var classString = '.' + id;

        //Check whether the tab has the "current" class
        if(!$(this).hasClass('current'))
        {
            //Remove any "current" classes
            $('.current').removeClass('current');

            //Add the current class
            $(this).addClass('current');
            $(classString).addClass('current');
        }
    });
    
    //Add click event to an object(s)
    addClickEventsToMoreButtons('a.more');
    addClickEventsToMoreAllButtons('a.more_all');

    //Add the onclick functions to the buttons
    $('a.host').click(function()
    {
        var host_id = $(this).attr('id');
        var path = window.location.pathname;

        $.ajax({
           type: 'POST',
           url: '../../library/class.ajaxCalls.php',
           data: 'host_id=' + host_id,
           success: function(msg)
           {
                alert( "Data Saved: " + msg );
           },
           error: function(xhr, ajaxOptions, thrownError)
           {
               var errorStatus = xhr.statusText;
               alert(errorStatus);
           }
         });

        return false;
    });

    $('#themes').change(function()
    {
        //Get the id of the select area
        var val = $("select#themes option:selected").val();
        var themesString = '';

        disableAllContent();

        if(val != 0)
        {
            //Highlight only the items belonging to this theme
            $('.themes').each(function()
            {
                var currentElement = $(this);
                themesString = $(this).text().replace(/ /g,'');
                console.info(themesString);
                var themeArray = themesString.split(',');
                var id = $(currentElement).attr('id');

                $.each(themeArray, function(index, value)
                {
                    if(value == val)
                    {
                        highlightContent(id.replace('themes',''), val);
                    }
                });
            });
        }
        else
        {
            //Highlight all the content
            highlightAllContent();
        }
    });

    //Add the tooltips
    //$(".tooltipContainer img[title]").tooltip();
    //$("#tooltip").tooltip({effect: 'slide'});
});

function addClickEventsToMoreButtons(object)
{
    //Add the onclick functions to the buttons
    $(object).click(function()
    {
        var anchor_tag = $(this);
        //Get the item content element
        var item_content = $(this).parent().next();

        //Toggle the content to be hidden or unhidden
        $(item_content).slideToggle(function()
        {
            //Check whether the item content is visible
            if($(item_content).is(':visible'))
            {
                //Make sure the correct button is displayed
                $(anchor_tag).addClass('less');
            }
            else
            {
                //Make sure the correct button is displayed
                $(anchor_tag).removeClass('less');
            }
        });

        return false;
    });
}

//Function to open all the items on the programme at the click of the "open all" button
function addClickEventsToMoreAllButtons(object)
{
    $(object).click(function()
    {
        //Initialise the item_content
        var item_content = '';

        if($(object).hasClass('less_all'))
        {
            closeAllItems();
            $(object).removeClass('less_all');
        }
        else
        {
            openAllItems();
            $(object).addClass('less_all');
        }
    });

    return false;
}

function closeAllItems()
{
    //Loop through all the items anchor tags
    $('a.more').each(function()
    {
        //Get the anchor tag and the individual item content
        var anchor_tag = $(this);
        var item_content = $(this).parent().next();

        //Check whether the item content is visible
        if($(anchor_tag).hasClass('less'))
        {
            $(item_content).css('display', 'none');
            $(anchor_tag).removeClass('less');
        }
    });
    return false;
}

function openAllItems()
{
    //Loop through all the items anchor tags
    $('a.more').each(function(i)
    {
        //Get the anchor tag and the individual item content
        var anchor_tag = $(this);
        var item_content = $(this).parent().next();

        //Check whether the item content is visible
        if(!($(anchor_tag).hasClass('less')))
        {
            //Toggle the content to be hidden or unhidden
            $(item_content).css('display', 'block');
            $(anchor_tag).addClass('less');
            
           
        }
    });
    return false;
}

function highlightContent(id, val)
{
    var content = $('#content' + id);
    var button = $('#morebutton' + id);

    if($(content).hasClass('disabled'))
    {
        $(content).removeClass('disabled');

        //Add click event to an object(s)
        addClickEventsToMoreButtons(button);
    }
}

function highlightAllContent()
{
    var content = $('.content_container');

    if($(content).hasClass('disabled'))
    {
        $(content).removeClass('disabled');

        //Add click event to an object(s)
        $('a.more').unbind('click');//Make sure they are all unbound first
        addClickEventsToMoreButtons('a.more');
    }
}


function disableAllContent()
{
    var content = $('.content_container');

    $(content).addClass('disabled');
    $('a.more').unbind('click');
}

function disableContent(id, val)
{
    var content = $('#content' + id);
    var button = $('#morebutton' + id);

    if(!$(content).hasClass('disabled'))
    {
        $(content).addClass('disabled');
        $(button).unbind('click');
    }
}
