$(document).ready(function(){

// activates data picker
       $(".datePick").datepicker({ dateFormat: 'dd/mm/yy' });

    // Flash media gallery embed
    if ($('#flashMediaWrap').length != 0 && typeof(mediaXMLSrc) != "undefined") {
    	
		swfobject.embedSWF("/assets/swf/media.swf?xmlSrc=" + mediaXMLSrc, "flashMediaWrap", "894", "518", "9.0.0", "/assets/swf/expressInstall.swf",
		{ xmlSrc: mediaXMLSrc },
		{ bgColor: '#f7f0db', menu: false, scale: 'noscale', flashvars: "xmlSrc=" + mediaXMLSrc, wmode: "transparent" },
		{ name: 'mediaGallery' });
    	
	}
	
	// Flash map embed
    if ($('#mainFlashReplace').length != 0 && typeof(mapXMLSrc) != "undefined") {
    	
		swfobject.embedSWF("/assets/swf/map.swf", "mainFlashReplace", "900", "375", "9.0.0", "/assets/swf/expressInstall.swf",
		{ xmlSrc: mapXMLSrc },
		{ bgColor: '#f7f0db', menu: false, scale: 'noscale', flashvars: "xmlSrc=" + mapXMLSrc, wmode: "transparent" },
		{ name: 'flashMap' });
    	
	}
	
	// Small flash map embed
    if ($('#destFlashReplace').length != 0 && typeof(mapXMLSrc) != "undefined") {
    	
    	var sMapFlashvars = { xmlSrc: mapXMLSrc };
		var sMapParams = { bgColor: '#f7f0db', menu: false, scale: 'noscale', wmode: "transparent", flashvars: "xmlSrc=" + mapXMLSrc };
		
		if (typeof(mapCountryId) != "undefined") {
			sMapFlashvars.mapCountryId = mapCountryId;
			sMapParams.flashvars += "&countryId=" + mapCountryId;
		} else if (typeof(mapRegionId) != "undefined") {
			sMapFlashvars.regionId = mapRegionId;
			sMapParams.flashvars += "&regionId=" + mapRegionId;
		}
    	
		swfobject.embedSWF("/assets/swf/smallMap.swf", "destFlashReplace", "278", "346", "9.0.0", "/assets/swf/expressInstall.swf",
		sMapFlashvars,
		sMapParams,
		{ name: 'flashMap' });
		
	}

// search box helper

   function inputHelper(theInput) {
       var orig = theInput.attr('value');
        theInput.focus(function() {
           if($(this).val() == orig) {
               $(this).val('');
           } 
        }).blur(function() {
            if($(this).val() == "") {
                $(this).val(orig);
            }
        });
   } 

// overlay 
    function overlayIsVisible() {
        if($('#overlay').is(':visible')) {
            return true;
        } else {
            return false;
        }
    }

    // if its one of the search pages, set searPage to true, and set theStartClass to the tab thats originally on.

    if($('#clickBar').length > 0) {
        theStartClass = $('#clickBar a').attr('tabOn');
        searchPage = true;
    } else {
        searchPage = false;
    }


    // make overlay big enough to cover screen, the hide it on load.
    $('#overlay').height($('#wrap').height()).hide().addClass('overlayWithJs');


    $('#tabBoxBottom').children('form').hide();

    $('.looking li a,#clickBar a').click(function() {
        if($(this).attr('tabOn') != null) {
            theClass = theStartClass;
        } else {
            theClass = $(this).parent().attr('class'); 
        }

        $('#tabBoxBottom').children('form').hide().filter('#'+theClass+'Form').show();
        $('.looking li a').removeClass('on');
        $('.'+theClass).children('a').addClass('on');

        // if the overlay isn't visible...        
        if(!overlayIsVisible()) {
            $('#overlay').fadeIn('fast');
            $('#bottomBar').hide();

        }
        return false;
    });

    overOver = false;

    $('#overInner').hover(function() {
       overOver = true; 
    }, function () {
        overOver = false;
    });

	$("#overInner select").mouseleave(function(event) { event.stopPropagation(); });

    $('#closeBox').hover(function() {
       overOver = false; 
    }, function () {
        overOver = true;
    });


    $('#overlay, #closeBox').click(function() {  
        if(!overOver) {
            $('#overlay').fadeOut('fast');
            if(searchPage) {
                $('.looking li a').removeClass('on');
                $('#pageLooking li.'+theStartClass+' a').addClass('on');

            } else {
                $('.looking li a').not('#pageLooking li a').removeClass('on');
            }
            $('#bottomBar').show();
        } 
    });








// Main Nav Hover Bubbles

    // Make bubble hover element.
    bubble = $('<p>').attr('id', 'bubble').css({display: 'none'});
    tips = new Array;

    // loop through tips attr on each li in the DOM, make assoc array
    $('#header ul li').each(function(i) {
        var theName = $(this).children().children().html();
        tips[theName] = $(this).attr('tip');
    });

    // add in the bubble
    $('#header').prepend(bubble);

    function getPosition(topLeft, theWidth) {
        return topLeft+(theWidth/2)-113;
    }




    $('#header ul li a, #bubble').hover(function() {
        //Add the correct tip to the bubble.
        if(tips[$(this).children().html()] != null) {
            $(bubble).html(tips[$(this).children().html()]);
            $('#bubble').css({left: getPosition($(this).position().left, $(this).width())}).show();
        }
    }, function() {
            $('#bubble').hide();
    });

    $('#bubble').hover(function() {
        $(this).show();
    }, function (){
        $(this).hide();
    });







// bottom bar

    inputHelper($('#loginUsername'));
    inputHelper($('#loginPassword'));
    inputHelper($('#LoginForm_Username'));
    inputHelper($('#LoginForm_Password'));

    if(!$('#loginBox').hasClass('open')) {
        $('#loginBox').hide();
        loginBoxVisible = false;
    } else {
        loginBoxVisible = true;
    }



    function loginBox() {
        if(!loginBoxVisible) {
            $('#loginBox').show();
            loginBoxVisible = true;
        } else {
            $('#loginBox').hide();
            loginBoxVisible = false;
        }
    }

    $('#bottomSignIn,#closeBoxLogin').click(function() {
        loginBox();
        return false;
    });

// homepage rotator

    if($('#home').length > 0) {

        theLength = $('#homeScroll .scrollBox').length;
        thePosition = theLength-1;
        rotateSpeed = 2500;
        fadeSpeed = 500;


        function fadeIt(theScroll) {
            if(thePosition != 0) {
                $('#homeScroll .scrollBox').eq(theScroll).fadeOut(fadeSpeed);
                thePosition--;
            } else {
                $('#homeScroll .scrollBox').eq(theLength-1).fadeIn(fadeSpeed, function() {
                    $('#homeScroll .scrollBox').show();
                });
                thePosition = theLength-1;
            }
            setTimeout(function(){
        		fadeIt(thePosition);
        	}, rotateSpeed);
        }

        setTimeout(function(){
    		fadeIt(thePosition);
    	}, rotateSpeed);        
    }



    if($('#homeSearch').length > 0) {
        inputHelper($('#homeSearch'));
    }

// search results page hovers
    
    if($('.result').length) {
        sendAway = false;
        
        if($('#searchResults').hasClass('out')) {
            sendAway = true;
            winWidth = screen.width - 200;
            winHeight = screen.height - 200;
        }
        $('.result').hover(function() {
            $(this).addClass('resultHover').children('.resultInner').children('.resultRight').children('h3').children('a').addClass('hover');
         }, function () { 
             $(this).removeClass('resultHover').children('.resultInner').children('.resultRight').children('h3').children('a').removeClass('hover');

        }).click(function() {
            theUrl = $(this).children('.resultInner').children('.resultRight').children('h3').children('a').attr('href');
            
            if(sendAway) {
                myRef = window.open(''+theUrl,'mywin',
                'left=50,top=50,width='+winWidth+',height='+winHeight+',toolbar=1,resizable=0');
                
            } else {
                window.location = theUrl
            }
        });
    }

// calendar functions

    if($('#cal').length > 0) {

        function monthName(month) {
            switch(month) {
                case 0:
                return "January";
                case 1:
                return "February";
                case 2:
                return "March";
                case 3:
                return "April";
                case 4:
                return "May";
                case 5:
                return "June";
                case 6:
                return "July";
                case 7:
                return "August";
                case 8:
                return "September";
                case 9:
                return "October";
                case 10:
                return "November";
                case 11:
                return "December";
                default:
                return "unknown";
            }
        }
        // determin number of days in a month        
        function daysInMonth(iMonth, iYear) {
        	return 32 - new Date(iYear, iMonth, 32).getDate();
        }

        // change the date object day from a Sunday start to a Monday Start!
        function dayToCalDay(iday) {            

            if(iday == 0) {
                calDay = 6;
            } else {
                calDay = iday-1;
            }
            return calDay;
        }

        function onDay(theDay) {
            if(onDaysArray) {
                
                for (var i=0; i < theDay.length; i++) {
                    $('#calTable tr').each(function() {
                        $(this).children('td:eq('+theDay[i]+')').addClass('on'); 
                    });
                };
                
                
            } else {
                $('#calTable tr').each(function() {
                   $(this).children('td:eq('+theDay+')').addClass('on'); 
                });
            }

        }

        // populate calendar based on the year / month
        function popCal(intMonth, intYear, intDay) {
            // if intDay is passed in, so a day needs the selected class...
            if(typeof intDay == 'undefined') {
                setTheDay = false;
            } else {
                setTheDay = true;
            }
            newDate = new Date();
            newDate.setFullYear(intYear);
            newDate.setMonth(intMonth);
            newDate.setDate(1);            
            startDay = dayToCalDay(newDate.getDay());
            iDay = 1;
            lastDay = daysInMonth(intMonth, intYear);
            $('#calTable td').removeClass('none');


            // if a day is being set...
            if(setTheDay) {
                $("#calTable td").each(function(i) {
                    $(this).html('');
                    if(iDay <= lastDay && i >= startDay) {
                        if(iDay == intDay) {
                            $(this).html(iDay).addClass('selected');
                        } else {
                            $(this).html(iDay);
                        }
                        iDay++;
                    } else {
                        // This is for the benefit of the hovers + clicks (don't work on null cells)
                        $(this).addClass('none');
                    }
                });
            } else {
                $("#calTable td").each(function(i) {
                    $(this).html('');
                    if(iDay <= lastDay && i >= startDay) {
                        $(this).html(iDay);
                        iDay++;
                    } else {
                        // This is for the benefit of the hovers + clicks (don't work on null cells)
                        $(this).addClass('none');
                    }
                });
            }



            $('#calInner div span').html(monthName(intMonth) + " " + intYear).attr("monthInt", intMonth).attr("yearInt", intYear);
        }

        // hovers for the cells + click to update date
        function bindCalEvents() {

            // The original total price at the bottom of the page
            theOriginalTotal = parseFloat($('#bookOneTotal').children('span').children('span').html());

            $('#calTable td').unbind();            
            if(onDays) {
                theCells = $('#calTable td').not('.none').filter('.on');
            } else {
                theCells = $('#calTable td').not('.none');
            }

            theCells.hover(function() {
                $(this).addClass('hover');
            }, function () {
                $(this).removeClass('hover');

            }).click(function() {
                    $('#calPrice').children('span').html('$').addClass('bLoading');
                    var intDay = $(this).html();
                    var intMonth = parseInt($('#calInner div span').attr("monthInt"))+1;
                    var intYear = $('#calInner div span').attr("yearInt");
                    var timestamp = intDay+intMonth+intYear;
                    $('#calTable td').removeClass('selected');
                    $(this).addClass('selected');
                    $('#calDate span').html($(this).html() + ", " + $('#calInner div span').html()).attr("timestamp", timestamp);
                    $('#oneDate').attr('timestamp', timestamp);
                    theUrl = window.location.pathname + "/GetPriceForDate";
                    theUrl = theUrl.replace("/booking2", "").replace("/accChange", "").replace("/removeAcc", "").replace("/add", "").replace("/remove", "");
                    $.ajax({
                      type: "GET",
                     // url: window.location.pathname+"/GetPriceForDate",
                     // url: "/cleanHTML/priceBack.html",
                     url: theUrl,
                      data: ({day: intDay, month: intMonth, year: intYear}),
                      success: function(msg){
                          money = new Array();
                          money = msg.split('*');

                          $('#calPrice').children('span:first').html(money[0]).removeClass('bLoading');
                          $('#calPrice').children('span:last').html(money[1]).removeClass('bLoading');
                          $('#bookOneTotal').children().children('span').html(money[2]);
                          $('#bookOneTotalDep').children().children('span').html(money[3]);

                      },
                      error: function(msg) {
                        alert(msg);  
                      }
                    });
            });
        }







        onDays = false;
        onDaysArray = false;
        var d  = new Date();
        if($('#calTable').attr('selectDate') == "true") {
            intMonth = parseInt($('#calTable').attr('selectMonth'));
            intYear = parseInt($('#calTable').attr('selectYear'));
            intDay = parseInt($('#calTable').attr('selectDay'));
            popCal(intMonth, intYear, intDay);

        } else{
            thisMonth = d.getMonth();
            thisYear = d.getFullYear();
            popCal(thisMonth, thisYear);
        }


        navDate = d;




        if($('#calTable').attr('onDay') != null) {
            
            theDays = $('#calTable').attr('onDay');
            if(theDays.length > 1) {
                daysArrayFirst = theDays.split(",");
                daysArray = new Array();
                for (var i=0; i < daysArrayFirst.length; i++) {
                    daysArray[i] = parseInt(daysArrayFirst[i]);
                };
                onDaysArray = true;
                
                onDay(daysArray);
                
            } else {
                onDay(parseInt($('#calTable').attr('onDay')));
            }
            
            // if there are only certain days a user can select from the cal, set this on.
            onDays = true; 
        }

        bindCalEvents();


        noBack = true;

        $('#calForward').addClass('hover').click(function() {
            navDate.setMonth(navDate.getMonth()+1);
            popCal(navDate.getMonth(), navDate.getFullYear());
            if(noBack = true) {
                noBack = false;
                $('#calBack').removeClass('stop');
            }

            $('#calTable td').removeClass('selected');
            bindCalEvents();
            return false;
        });

        $('#calBack').click(function() {

           if(!$(this).hasClass('stop')) {
                navDate.setMonth(navDate.getMonth()-1);
                popCal(navDate.getMonth(), navDate.getFullYear());
            //    alert(navDate+" is equal to"+ d);
                if(navDate.getMonth() == thisMonth && navDate.getFullYear() == thisYear) {
                    noBack = true;
                    $('#calBack').addClass('stop');
                }
                $('#calTable td').removeClass('selected');
                bindCalEvents();
           }
           return false;

        });





    }

    if($('.teacher').length > 0) {
        $('.teacherMore').hide();

        $('.teacher .blueBlock').toggle(function(){
            $(this).next().slideDown('fast');
            return false;
         }, function () {   
            $(this).next().slideUp('fast');
            return false;
        });
    }

    if($('#teflEmployer').length > 0) {
        $('#empClose').click(function() {
           $(this).parent().hide();
           return false; 
        });
    }


//  reivew page star system


    if($('#reviewStars').length > 0) {

        function magicStar(theStar) {
            theStar.children().removeClass('off').html('on');
            if(theStar.prev().length > 0) {
                theNext = theStar.prev();
                theNext.children().removeClass('off').html('on');
                magicStar(theNext);
            }
        }

        function setStarVal(oElement) {
            var starVal =  oElement.parent().children(oElement.nodeName).index(oElement)+1;
            theId = oElement.parent().attr('class');
            $('#'+theId).val(starVal);
        }

        $('#reviewStars a').click(function() {                        
            starBlock = $(this).parent().parent();
            starBlock.children().children().removeClass('off').addClass('off').html('Off'); 
            magicStar($(this).parent());

            setStarVal($(this).parent());
            return false;
        });

    }


    if($('#courseRes').length > 0) {
        theUrl = window.location.href;
        theNumber = theUrl.match(/\d+$/);
        $('.courseResMore').each(function(i) {
            $(this).attr('moreTarg', 'moreTarg'+i).parent().parent().next().attr('id', 'moreTarg'+i).hide(); 
                
        }).click(function() {
            if($('#'+$(this).attr('moreTarg')).is(":visible")) {
                $('#'+$(this).attr('moreTarg')).hide();
                
            } else {
                $('#'+$(this).attr('moreTarg')).show();
                
            }
            return false;
        });
        
        $('#'+theNumber).next().show();

    }

});

// END jquery





// fonts we're using

var blue = {
   src: '/assets/swf/blueHighway.swf',
   selectable: true
 };



//activate them

sIFR.activate(blue);

//target elements to replace



sIFR.replace(blue, {
   selector: '.bottomTitle'
   ,css: [
     'a { font-size: 26px; color: #525252; text-decoration: none}',
     'a:hover {color: #000000}'

   ],
   wmode: 'transparent'
});

sIFR.replace(blue, {
   selector: '.blueTwentySix'
   ,css: [
     '.sIFR-root { font-size: 26px; color: #2e8377;}'

   ],
   wmode: 'transparent'
});

sIFR.replace(blue, {
   selector: '.blueTwentyFour'
   ,css: [
     '.sIFR-root { font-size: 23px; color: #2e8377;}'

   ],
   wmode: 'transparent'
});

sIFR.replace(blue, {
   selector: '.blueGreen'
   ,css: [
     '.sIFR-root { font-size: 26px; color: #4f9b2a;}'

   ],
   wmode: 'transparent'
});

sIFR.replace(blue, {
   selector: '.bluePink'
   ,css: [
     '.sIFR-root { font-size: 26px; color: #933f8a;}'

   ],
   wmode: 'transparent'
});


sIFR.replace(blue, {
   selector: '.blueThirty'
   ,css: [
     '.sIFR-root { font-size: 30px; color: #2e8377;}'

   ],
   wmode: 'transparent'
});

sIFR.replace(blue, {
   selector: '#yourRef'
   ,css: [
     '.blueBlue { font-size: 26px; color: #32827b;}',
      '.blueGrey { font-size: 26px; color: #a2a2a2;}'

   ],
   wmode: 'transparent'
});

sIFR.replace(blue, {
   selector: '#whatFind div h3'
   ,css: [
     '.sIFR-root { font-size: 21px; color: #686868;}'

   ],
   wmode: 'transparent'
});


/*FANCY BOX EXAMPLE

if ($('.imgRight').length > 0) {
    $("a.fancy").fancybox({
        'zoomSpeedIn': 200,
        'zoomSpeedOut': 200,
        'overlayShow': true,
        'overlayOpacity': 0
    });
}*/

