function initSifr(colorA, colorB) {
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({sSelector:"#header-copy h1", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorB, sWmode:"transparent"}));
		//sIFR.replaceElement(named({sSelector:"#header-copy p", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorB, sWmode:"transparent"}));
		sIFR.replaceElement(named({sSelector:"#content h1", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent", nPaddingBottom:15}));
		sIFR.replaceElement(named({sSelector:"#content p.intro", sFlashSrc:"/swf/georgia.swf", sColor:"#666666", sWmode:"transparent"}));
		sIFR.replaceElement(named({sSelector:"#results h2", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent"}));
		sIFR.replaceElement(named({sSelector:"#results h3", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent", nPaddingBottom:7}));
		sIFR.replaceElement(named({sSelector:"#wrapper h2", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent", nPaddingTop:17, nPaddingRight: 20, nPaddingBottom:15, nPaddingLeft: 20}));
		sIFR.replaceElement(named({sSelector:".feature h2", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent"}));
		sIFR.replaceElement(named({sSelector:".feature-white h2", sFlashSrc:"/swf/verdana.swf", sColor:"#808071", sWmode:"transparent", sCase:"upper", nPaddingTop:10, nPaddingRight: 10, nPaddingBottom:8, nPaddingLeft: 10}));
		sIFR.replaceElement(named({sSelector:".whitepanel h2", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent"}));
		sIFR.replaceElement(named({sSelector:".whitepanel h3", sFlashSrc:"/swf/georgia.swf", sColor:"#"+colorA, sWmode:"transparent", nPaddingBottom:7}));
	};
}

function initPopups() {
	$("a[rel='pop-up']").click(function() {
		var features = "height=713,width=525,scrollTo,resizable=0,scrollbars=1,location=0";
		newwindow=window.open(this.href, 'Popup', features);
		return false;
	});
}

function initMenuMain() {
    $("#mm li a").hover(
		function() {
		    $("body").toggleClass("on");
		},
		function() {
		    $("body").toggleClass("on");
		}
	);
}

function initSideNav() {
    $(document).ready(function() {
        $("ul.menu li").mouseover(function() {
            $(this).addClass("sfhover");
        });
        $("ul.menu li").mouseout(function() {
            $(this).removeClass("sfhover");
        });
    });

}

function initSearch() {
	$("#q").focus(function () {
		var txt = ($(this).val() == "Search") ? "" : $(this).val();
		$(this).val(txt);
	});
	$("#q").blur(function () {
		var txt = ($(this).val() == "") ? "Search" : $(this).val();
		$(this).val(txt);
	});
	$("#go").click(function () {
	    window.location = "/search.aspx?search=" + $("#q").val();
		//$(this).parent().submit();	
		return false;
	});
	// Submit form when enter is pressed in textfield
	$("#q").keypress(function(e){
      if(e.which == 13){
       window.location = "/search.aspx?search=" + $("#q").val();
		//$(this).parent().submit();	
		return false;
       }
      });
}

function in_array(needle, haystack, argStrict) {
    var found = false, key, strict = !!argStrict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}

function initCalendar(month, year, start_day, homepage){
	
	var is_homepage = !!homepage;
	
	var month_name=['January','February','March','April','May','June','July','August','September','October','November','December'];
	var days_in_month=[31,0,31,30,31,30,31,31,30,31,30,31];
	
	if(start_day<1 || start_day>7)start_day=1;
	
	var date = new Date(year, month-1, 1); //DD replaced line to fix date bug when current day is 31st
	date.day=date.getDay()+1; //DD replaced line to fix date bug when current day is 31st
	
	var tmp_date=date.day-start_day;
	if(tmp_date<0)tmp_date=7+tmp_date;
	date.day=tmp_date+1;
	
	var week_str="SMTWTFS".substr(start_day-1,"SMTWTFS".length)+"SMTWTFS".substr(0,start_day-1);
	
	var now=new Date() //DD
	var today=(year==now.getFullYear() && month==now.getMonth()+1)? now.getDate() : 0 //DD
	
	days_in_month[1]=(((date.getFullYear()%100!=0)&&(date.getFullYear()%4==0))||(date.getFullYear()%400==0))?29:28;
	
	var table='<table cellpadding="0" cellspacing="0" border="0" id="calendar">';
	table+='<tr>';
	table+='<th><a href="#" id="cal-prev" title="Previous">Prev</a></th>';
	table += '<th colspan="5"><div class="squirly-left"><div class="squirly-right"><a href="/social-season/events-by-month/' + month_name[month - 1].toLowerCase() + '-'+ year +'.aspx">' + month_name[month - 1] + ' ' + year + '</a></div></div></th>';
	table+='<th><a href="#" id="cal-next" title="Next">Next</a></th>';
	table+='</tr>';
	
	table+='<tr>';
	
	for(s=0;s<7;s++) {
		table+='<th><span>'+week_str.substr(s,1)+'</span></th>';
	}
	
	table+='</tr>';
	table+='<tr>';
		
	for(i=1;i<=42;i++){
	    var this_day = ((i - date.day >= 0) && (i - date.day < days_in_month[month - 1])) ? '<span id="day_' + (i - date.day + 1) + '"><a href="/social-season/events-by-month/' + month_name[month - 1].toLowerCase() + '-'+ year +'.aspx">' + (i - date.day + 1) + '</a></span>' : '&nbsp;';
		if (i-date.day+1==today) {
			this_day = this_day; // Add special formatting for today
		}
		
		table+='<td>'+this_day+'</td>';

		if (((i) % 7 == 0) && (i < 36) && this_day == '&nbsp;' || ((i) % 7 == 0) && (i < 36) && this_day == '<span id="day_' + (days_in_month[month - 1]) + '"><a href="/social-season/events-by-month/' + month_name[month - 1].toLowerCase() + '-'+ year +'.aspx">' + (days_in_month[month - 1]) + '</a></span>') {
			table+='</tr>';
			break;
		} else if(((i)%7==0)&&(i<36) && this_day != '&nbsp;') {
			table+='</tr><tr>';
		}
	}
	
	table+='</tr>';
	table+='</table>';
	$("#cal-container").html(table);
//	$("#cal-prev").click(function() { month = (month>1) ? month-1 : 12;	year = (month>1) ? year : year-1;	initCalendar(month ,year, start_day); return false;});
//	$("#cal-next").click(function() { month = (month<12) ? month+1 : 1; year = (month<12) ? year : year+1;	initCalendar(month ,year, start_day); return false;});
    $("#cal-prev").click(function() { var prev_month = month; month = (month>1) ? month-1 : 12;   year = (prev_month==1&&month==12) ? year-1 : year;     initCalendar(month ,year, start_day, is_homepage); return false;});
    $("#cal-next").click(function() { var prev_month = month;  month = (month<12) ? month+1 : 1; year = (prev_month==12&&month==1) ? year+1 : year;     initCalendar(month ,year, start_day, is_homepage); return false;});

	
	$.ajax({
		type: "GET",
		url: "/calendarasjson.aspx",
		data: "month="+month+"&year="+year+"&num=999",
		dataType: "json",
		success: function(data) {
			var i = 1;
			$("#cal-links").empty();
			jQuery.each(data.Events, function() {
				var style = (i>6) ? ' style="display: none;"' : "";
				$("#cal-links").append('<li'+style+' class="event_'+i+'"><a href="'+this.Url+'" id="event_'+i+'">'+this.EventName+'</a></li>');
				jQuery.each(this.Dates, function() {
					$("#day_"+this).addClass("event_"+i);	 
				});
				i++;
			});
			$("#cal-links li a").hover(function () { $("#calendar span."+$(this).attr("id")).toggleClass("highlight");}, function () { $("#calendar span."+$(this).attr("id")).toggleClass("highlight");});
			if (is_homepage) { $("#calendar td a").hover(function () { var links = $(this).parent().attr("class").split(" "); jQuery.each($("#cal-links li"), function() { if(in_array($(this).attr('class'), links)) { $(this).show(); } else { $(this).hide(); }});}, function () { /* do something on rollout */ }); }
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
				switch (XMLHttpRequest.status) {
					case 404:
						$("#cal-links").html('<li><a href="#" onclick="return false;">Web service not found</a></li>');
						break;
					default:
						$("#cal-links").html('<li><a href="#" onclick="return false;">Error loading events list</a></li>');
						break;
				}
			}
	});
}

function initTabs() {
	$("#tabs").tabs();	
}

function initRegister() {
	$("#register-cancel").click(function () {
		$(".debrettsForm").clearForm();	
		return false;
	});
}

function initPeopleSearch() {
	$("#basic-search").click(function () {
	loadPeopleSearchResults($("#basic-form").serialize(), 1, "results", true);
		return false;
	});
	$("#advanced-search").click(function () {
	loadPeopleSearchResults($("#advanced-form").serialize(), 1, "results", true);
		return false;
	});
	$("#advanced-cancel").click(function () {
		$("#advanced-form").clearForm();	
		return false;
	});
	$('#searchString').keypress(function(e){
      if(e.which == 13){
          loadPeopleSearchResults($("#basic-form").serialize(), 1, "results", true);
        e.preventDefault();
        return false;
      }
    });	
    $('.adv').keypress(function(e){
        if(e.which == 13){
		    loadPeopleSearchResults($("#advanced-form").serialize(), 1, "results", true);
            e.preventDefault();
		    return false;
		}
    });

    //CheckQueryString and search if it has value
    if ($.query.get("search").toString() != 'true' && $.query.get("search").toString() != '') {
        $("#searchString").val($.query.get("search").toString());
        loadPeopleSearchResults($("#basic-form").serialize(), 1, "results", true);
    }
}

function loadPeopleSearchResults(queryString, pageIndex, resultsDivId, showResults) {
     var pageSize = 10;
     $.ajax({
       url: "/SearchPeopleOfToday.aspx?"+queryString+"&pageIndex="+pageIndex+"&pageSize="+pageSize,
       cache: false,
       success: function(html) {
           if (showResults) $("#" + resultsDivId).show();
           $("#data_"+window.current).removeClass("current");
           $("#data").empty();
           $("#data").append(html);
           $("#data_"+pageIndex).addClass("current");
           window.current = pageIndex;
       }
     });
     $.ajax({
       url: "/SearchPeopleOfToday.aspx?"+queryString+"&pageIndex="+pageIndex+"&pageSize="+pageSize+"&countOnly=1",
       cache: false,
       success: function(pagesTotal){
             var str = '';
             for (var i = 1; i<=pagesTotal; i++) {
                 var myclass = (i == pageIndex) ? ' current' : '';
                str += '<a href="#" id="data_'+i+'" onclick="loadPeopleSearchResults(\''+queryString+'\','+i+',\''+resultsDivId+'\','+showResults+'); return false;" class="page'+myclass+'">'+i+'</a> ';
             }
             if(pagesTotal==0) {
                $("div.paging").hide();
             } else {
                $("div.paging").show();
             }
             $("#pages").html(str);
       }
     });
}

function toggleMore(id) {
	if($("#more_"+id).is(":hidden")) {
		$("#more_"+id).show();
		$("#link_"+id).text("Hide more information");
	} else {
		$("#more_"+id).hide();
		$("#link_"+id).text("Show more information");
	}
}

var Events = new Array();
var currentEvent = 1;
var clicked = false;
var began = false;
var duration = 4000;

function initTwizzler() {
     $.ajax({
           type: "GET",
           url: "/HomePageJSON.aspx",
           data: '',
           dataType: "json",
           success: function(data) {
                var i = 1;
                var strRight = "";
                var strText = "";
                var strNav = "";
                jQuery.each(data.Events, function() {
                     var Event = new Object();
                     Event["ID"] = i;
                     Event["IntroText"] = this.IntroText;
                     Event["Title"] = this.Title;
                     Event["Subtitle"] = this.Subtitle;
                     Event["Description"] = this.Description;
                     Event["LinkText"] = this.LinkText;
                     Event["Url"] = this.Url;
                     Event["Image"] = this.Image;
                     Events.push(Event);
                                                           
                     strText += (i==1) ? '<h3>'+this.IntroText+'</h3>' : '';
                     strText += (i==1) ? '<h2>'+this.Title+'</h2>' : '';
                     strText += (i==1 && this.Subtitle!=='') ? '<p>'+this.Subtitle+'</p>' : '';
                     strText += (i==1) ? '<p>'+this.Description+'</p>' : '';
                     //strText += (i==1) ? '<a href="#" class="bullet">'+this.LinkText+'</a>' : '';
                     strText += (i==1) ? '<a href="'+this.Url+'" class="bullet">'+this.LinkText+'</a>' : '';
                     
                     strRight += (i==1) ? '<div id="img_'+i+'"><img src="'+this.Image+'" width="540" height="270" alt="" /></div>' : '<div id="img_'+i+'" style="display: none;"><img src="'+this.Image+'" width="540" height="270" alt="" /></div>';
                     strNav += (i==1) ? '<li><a href="#" class="current" id="link_'+i+'">'+i+'</a></li>' : '<li><a href="#" id="link_'+i+'">'+i+'</a></li>';
                     i++;
                });
                
                $("#twizzler-right").html(strRight); 
                $("#twizzler-left").html(strText);   
                $("#twizzler-nav").html(strNav);
                switchTwizzler();
                switchTimed();
           },
           error: function(XMLHttpRequest, textStatus, errorThrown) {
                     switch (XMLHttpRequest.status) {
                           case 404:
                                $("#twizzler-left").html('<h3>Web service not found</h3>');
                                break;
                           default:
                                $("#twizzler-left").html('<h3>Error loading events list</h3>');
                                break;
                     }
                }
     });
}

function switchTimed() {
     var nextEvent = (currentEvent==Events.length) ? 1 : currentEvent+1;
     if (began && !clicked) {
         switchContent(currentEvent, nextEvent - 1);
     }
     began = true;
     if (!clicked) {
         timer = setTimeout("switchTimed()", duration);
     } else {
        clicked = false;
        timer = setTimeout("switchTimed()", duration*2);
     }
}

function switchContent(from, to) {
     $("#img_"+from).fadeOut("medium"); 
     $("#link_"+from).removeClass("current"); 
     
     $("#img_"+(to+1)).fadeIn("medium"); 
     $("#link_"+(to+1)).addClass("current");
     
     var strText = '<h3>'+Events[to]["IntroText"]+'</h3>';
     strText += '<h2>'+Events[to]["Title"]+'</h2>';
     strText += (Events[to]["Subtitle"]!=='') ? '<p>'+Events[to]["Subtitle"]+'</p>' : '';
     strText += '<p>'+Events[to]["Description"]+'</p>';
     //strText += '<a href="#" class="bullet">'+Events[to]["LinkText"]+'</a>';    
     strText += '<a href="'+Events[to]["Url"]+'" class="bullet">'+Events[to]["LinkText"]+'</a>';
     
     $("#twizzler-left").html(strText);
     currentEvent=to+1;
}

function switchTwizzler() {

    $("#twizzler-nav li a").click(
     function() {
         var i = this.firstChild.nodeValue - 1;

         if (currentEvent != i + 1) {
             switchContent(currentEvent, i);
         }
         clicked = true;
         return false;
     });
}


function initQuotes() {
    getQuote();
}

function getQuote() {
    $.getJSON("/quotes.aspx", function(data, textStatus) {
        if (textStatus == "success") {
            var quote = "";
            if (data.url != "") quote += '<a href="' + data.url + '">';
            quote += '<img alt="' + data.quote + '" src="/umbraco/imagegen.ashx?text=' + data.quote +
                '&antialias=true&fontsize=9&fontstyle=regular&font=georgia&valign=middle&fontcolor=808071&bgcolor=f7f7f0" />&nbsp;';
            quote += '<em>';
            quote += '<img alt="' + data.author + '" src="/umbraco/imagegen.ashx?text=' + data.author +
                '&antialias=true&fontsize=9&fontstyle=italic&font=georgia&valign=middle&fontcolor=808071&bgcolor=f7f7f0" />';
            quote += "</em>";
            if (data.link != "") quote += "</a>";
            $("#quote p").html(quote);
        }
    });
    var quoteTimer = 0;
    quoteTimer = window.setTimeout(getQuote, 10000);
}

function initByNamePaging() {
    var pagerDiv = "<div id=\"pager\" />";
    $(".browsePeople").append(pagerDiv);

    //hide all pages
    $(".browsePeople div").hide();

    $("#pager").pager({ pagenumber: 1, pagecount: $(".browsePeople div").length - 1, buttonClickCallback: PageClick });

    $("#page1").show();
    $("#pager").show();
}

PageClick = function(pageclickednumber) {
    $("#pager").pager({ pagenumber: pageclickednumber, pagecount: $(".browsePeople div").length - 1, buttonClickCallback: PageClick });
    $(".browsePeople div").hide();
    $("#page" + pageclickednumber).show();
    $("#pager").show();
}


function initDatePicker() {
    //Dependent on the following:
    // Day select called #day
    // Month select called #month
    // Year select called #year
    // Date hidden field called #dateOfBirth which will either have an empty value or
    // a val in the following formats: dd/mm, dd/mm/yyyy, yyyy
    $("#day").change(function() {
        changeDate();
    });

    $("#month").change(function() {
        changeDate();
    });

    $("#year").change(function() {
        changeDate();
    });
}

function changeDate() {
    $("#dateOfBirth").val('');
    if ($("#day").val() != '') {
        if ($("#month").val() != '' && $("#year").val() != '') {
            $("#dateOfBirth").val($("#day").val() + '/' + $("#month").val() + '/' + $("#year").val());
        }
        else if ($("#month").val() != '' && $("#year").val() == '') {
            $("#dateOfBirth").val($("#day").val() + '/' + $("#month").val());
        }
    }
    if ($("#month").val() != '') {
        if ($("#day").val() != '' && $("#year").val() != '') {
            $("#dateOfBirth").val($("#day").val() + '/' + $("#month").val() + '/' + $("#year").val());
        }
        else if ($("#day").val() != '' && $("#year").val() == '') {
            $("#dateOfBirth").val($("#day").val() + '/' + $("#month").val());
        }
    }
    if ($("#year").val() != '') {
        if ($("#day").val() == '' && $("#month").val() == '') {
            $("#dateOfBirth").val($("#year").val());
        }
        else if ($("#day").val() == '' || $("#month").val() == '') {
            //do nothing
        }
        else {
            $("#dateOfBirth").val($("#day").val() + '/' + $("#month").val() + '/' + $("#year").val());
        }
    }
}

function logout() {
    if (window.confirm("Are you sure you wish to log out?")) {
        var logoutUrl = window.location;
        if (logoutUrl.toString().indexOf("?") == -1) {
            logoutUrl = logoutUrl + "?";
        }
        logoutUrl = logoutUrl + "&altTemplate=AsyncLogout";

        $.ajax({
            type: "GET",
            url: logoutUrl,
            success: function(msg) {
                alert("You have been logged out.");
                window.location = window.location;
            }
        });
    }
}