﻿/*

File:		eqtr_functions.js
Created:	27/03/09
Author:		Jamie Boyd @ Equator	

Notes:


*/


var googleApi = "http://www.google.com/jsapi?key=" + googleKey;

///////////////////////
// Form Inline Labels//
///////////////////////


$(function() {


    // Full Width Spanning

    if ($("#subContent *").length == 0) {
        $("#mainContent").css("padding-right", "331px");

    }


    $(".subNav ul li:last-child").addClass("last");

    $("#subContent > div:first-child").addClass("first");

    $("#header .mainSearch input[type=text]").each(function() {
        var labelVal = $("#header .mainSearch label.searchLabel").text();

        $(this).each(function() {
            createText(labelVal, $(this));
        });
        // Removal of text on user-focus
        $(this).focus(function() {
            removeText(labelVal, $(this));
        });
        // Restoration of default text on input blur, if no user input.
        $(this).blur(function() {
            restoreText(labelVal, $(this));
        });
    });

    $(".homepage #courseSearch input[type=text]").each(function() {
        var labelVal = $(".homepage #courseSearch label").text();
        $(this).each(function() {
            createText(labelVal, $(this));
        });
        // Removal of text on user-focus
        $(this).focus(function() {
            removeText(labelVal, $(this));
        });
        // Restoration of default text on input blur, if no user input.
        $(this).blur(function() {
            restoreText(labelVal, $(this));
        });
    });

    $("#footer .newsletter input[type=text]").each(function() {
        var labelVal = $("#footer .newsletter label").text();
        $(this).each(function() {
            createText(labelVal, $(this));
        });
        // Removal of text on user-focus
        $(this).focus(function() {
            removeText(labelVal, $(this));
        });
        // Restoration of default text on input blur, if no user input.
        $(this).blur(function() {
            restoreText(labelVal, $(this));
        });
    });

    // Features Carousel //

    // Setup

    //$(".featureCarousel ul li").eq(0).addClass("active");

    $(".featureCarousel ul li").each(function() {

        var link = $(this).find("a").eq(0).attr("href");

        if (link) {
            // Add link button at end of intro text        
            var newLink = document.createElement("a");
            $(newLink).attr("href", link).addClass("featLink");
            var newLinkContent = document.createElement("span");
            $(newLinkContent).text(" (Read more)");
            $(newLink).append(newLinkContent);
            //$(this).find("p.intro").eq(0).append(newLink);
        }
        // Get text from inside <h2>+<a>, remove <a> and reinsert text in <h2>      
        //        var featHead = $(this).find("a").eq(0).text();
        //        $(this).find("a").eq(0).remove();
        //        $(this).find("h2").eq(0).text(featHead);


        if ($("body.homepage").length) {
            // Create overlay from exising content and add to feature
            var heading = $(this).find("h2").eq(0).text(); ;
            var intro = "Read more about this feature: " + $(this).find("h2").eq(0).text();
            var featImage = $(this).find("p.featImage").eq(0);
            var overlay = document.createElement("div");
            $(overlay).addClass("overlay");
            var overlayHead = document.createElement("h3");
            $(overlayHead).text(heading);
            var overlayLink = document.createElement("p");
            var overlayAnchor = document.createElement("a");
            $(overlay).append(overlayHead);
            if (link) {
                $(overlayAnchor).attr("href", link).attr("title", intro).text("Read more");
                $(overlayLink).append(overlayAnchor);
                $(overlay).append(overlayLink);
            }


            $(this).append(featImage);
            $(this).append(overlay);
        }

        $(".featureCarousel ul li").eq(0).addClass("active");
        $(".homepage .featureCarousel ul li").eq(0).removeClass("active");

    });

    $(".featureCarousel ul li").hover(function() {

        $(".featureCarousel ul li").removeClass("active");
        $(this).addClass("active");
    }, function() {

    });

    $("table tr:nth-child(odd)").addClass("odd");

    $(".interests ul li:nth-child(odd)").addClass("odd");


    ///////////////////////////////////
    // Application Validation Method //
    ///////////////////////////////////

    $(".applyConf .button input").click(function() {

        //checkErrors();


    });


    ///////////////////////////////
    // Homepage Schools Scroller //
    ///////////////////////////////

    $(".schoolsGuide").addClass("scroller");

    // get width of schools panels in scroller
    if ($(".schoolsGuide .inner li").length > 0) {

        // Size of visible panel
        var visWidth = 482;
        // Size of school panel (+ margin)
        var imgWidth = 241;
        var imgNum = $(".schoolsGuide .inner li").length;
        // Set width of schools ul based on number of schools
        var scrollerWidth = imgWidth * imgNum;
        $(".scroller ul").css("width", scrollerWidth);
        var pageNum = scrollerWidth / visWidth;
        pageNum = Math.round(pageNum);

        // Setup Scroller Controls

        var controls = document.createElement("div");
        $(controls).addClass("scrollControls");

        var leftBut = document.createElement("a");
        $(leftBut).addClass("leftBut").addClass("lEnd").text("Previous");
        var rightBut = document.createElement("a");
        $(rightBut).addClass("rightBut").text("Next");

        var scrollBullets = document.createElement("div");
        $(scrollBullets).addClass("scrollBullets");

        for (i = 0; i < pageNum; i++) {
            var bullet = document.createElement("a");
            $(bullet).addClass("bullet");
            var spacer = document.createElement("img");
            $(spacer).attr('src', "../images/scroller_bullet_spacer.gif").attr('width', "15").attr('height', "14").attr('alt', "");
            $(bullet).append(spacer);
            $(scrollBullets).append(bullet);
        }

        $(scrollBullets).find("a").eq(0).addClass("currentPage");
        $(controls).append(leftBut).append(rightBut).append(scrollBullets);
        $(".schoolsGuide .schools").append(controls);

        var currPage = 1;
    }

    $(".scrollBullets a").click(function() {
        var clickIndex = $(this).parent().find("> *").index(this);
        var margin = visWidth * clickIndex;

        var length = $(this).parent().find("> *").length;

        if (clickIndex == 0) {
            $(".leftBut").addClass("lEnd");
            $(".rightBut").removeClass("rEnd");
        }
        else if (clickIndex == (length - 1)) {
            $(".rightBut").addClass("rEnd");
            $(".leftBut").removeClass("lEnd");
        }
        else {
            $(".leftBut").removeClass("lEnd");
            $(".rightBut").removeClass("rEnd");
        }


        $(this).parents(".schools").eq(0).find("ul").animate({ marginLeft: -margin }, 500);
        $(".scrollBullets a").removeClass("currentPage");
        $(this).addClass("currentPage");
        currPage = clickIndex + 1;

    });

    $(".rightBut").click(function() {
        var currMargin = $(this).parent().find("ul").css('margin-left');
        currMargin = parseInt(currMargin);
        if (currPage < pageNum) {
            $(".leftBut").removeClass("lEnd");
            $(this).parents(".schools").eq(0).find("ul").animate({ marginLeft: "-=482" }, 500);
            currPage = currPage + 1;
            $(".scrollBullets a").removeClass("currentPage");
            $(".scrollBullets a").eq(currPage - 1).addClass("currentPage");
            if (currPage == pageNum) {
                $(".rightBut").addClass("rEnd");
            }
        }
    });

    $(".leftBut").click(function() {
        var currMargin = $(this).parent().find("ul").css('margin-left');
        currMargin = parseInt(currMargin);
        if (currPage > 1) {
            $(".rightBut").removeClass("rEnd");
            $(this).parents(".schools").eq(0).find("ul").animate({ marginLeft: "+=482" }, 500);
            currPage = currPage - 1;
            $(".scrollBullets a").removeClass("currentPage");
            $(".scrollBullets a").eq(currPage - 1).addClass("currentPage");
            if (currPage == 1) {
                $(".leftBut").addClass("lEnd");
            }
        }
    });


    //////////////////////////////
    // Subjects Guide Show/Hide //
    //////////////////////////////

    $(".subjectsGuide .details").hide();

    $(".subjectsGuide h3").click(function() {
        $(this).toggleClass("open");
        $(this).parent().find(".details").slideToggle();

    });


    ///////////////////////
    // Tablet tab panels //
    ///////////////////////

    // Add "selected" class to the first tab (li) in the tablet
    $(".tablet").each(function() {
        $(this).contents().find("li").each(function(e) {
            if (e < 1) {
                $(this).addClass("selected");
            }
            else { }
        })
    });

    // Make first panel visible and hides others //
    $(".tablet").each(function() {
        $(this).contents().find(".section").each(function(e) {
            if (e < 1) {
            }
            else { $(this).hide(); }
        });
    });

    // On tab click, show corresponding panel and hide others
    $(".tablet .controls a").click(function() {
        // Find position of clicked tab in array of tabs
        var currListItem = $(this).parent();
        var tabIndex = $(this).parent().parent().find('> *').index(currListItem);

        $(this).parents(".tablet").eq(0).find(".section").each(function() {
            // Find position of each content section in array of sections
            var sectionIndex = $(this).parent().find('> *').index(this);
            // If index of content section matches index of clicked tab -> Show Content
            if (tabIndex == sectionIndex) {
                $(this).show();
            }
            // Otherwise hide content
            else { $(this).hide(); }
        });
        // Set "selected" class on clicked tab (li) 
        $(this).parents(".tablet").eq(0).find(".controls a").each(function() {
            $(this).parents("li").eq(0).removeClass("selected");
        });
        $(this).parents("li").eq(0).toggleClass("selected");
        // Disable link
        $(this).blur();
        return false;
    });


    // setup google map
    if ($(".googleMap").length) {
        $.getScript(googleApi, loadGoogleMapApi);
    }

    // initialise google link tracking
    setGoogleLinks();

});

// google link tracking code. Uses jquery
function setGoogleLinks() {

    // Variable for urls that are NOT external
    // Reg Exp matching. Urls are delimited by the pipe | and dots are escaped with \.
    // Most bases are covered with location.host, but there are the situations
    // where it might link to a sub-domain e.g. www.site.com --> secure.site.com
    // For sub-domain cases you just need the domain part of the url and it will be matched for all subdomains
    var onsiteUrls = location.host + "|" + "\.lewisham\.ac\.uk";

    // Variable for download file extensions. Assumes that the file type is at the end of the href.
    // Uses reg exp. File types are delimited by the pipe |
    var downloadDocTypes = "(pdf|doc|docx)$";

    // The page that the link was requested from. Removes any leading or ending forward slash
    var pageLocation = unescape(location.pathname.replace(/(^\/)|(\/$)/g, ""));

        // regular expression for external site testing
    var site = new RegExp( onsiteUrls , "ig" );
        // regular expression for downloads
    var download = new RegExp( downloadDocTypes , "ig" );

    $("a").each(function(e) {

		// Local variable for holding the action. Don't need to change. Current actions handled are
		// mailto, download and external
		var action = "";

        // don't track for javascript links and bookmarks
        if (this.href.match(/(^javascript)|(^#)/) || !this.href) return true;

        // mailto
        if( this.href.match(/mailto/ig) )
        {
            action = "mailto";
        }
        // download
        else if( this.href.match( download ) )
        {
            action = "download";
        }
        // external link
        else if( !this.href.match( site ) )
        {
			action = "external";
        }

        // if there is an action identified add a click event handler.
        if (action) {

			// use the href of the link as an identifier. Strip out the http protocol from the front and trailing forward slash
			var thisLink = this.href.replace(/http[s]*:\/\/|\/$/g, "");
			var googlePageview = "/" + action + " / " + thisLink + " / " + pageLocation;

            $(this).click(function() {

                // debugging for FF and safari
//                console.info(action);
//                return false;
                // End debug
                
                /* Can use pageview or event tracking or both. */

                // Use page view to track links
                pageTracker._trackPageview(googlePageview);

                // Use event tracking to track links
                pageTracker._trackEvent("Links", action, "TO: " + thisLink + "; FROM: " + pageLocation);
            });
        }

    });
}


// Create default text for text field on page load
function createText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {

        if (thisObj.attr("value") == defVal || thisObj.attr("value").length == 0) {

            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}

// Remove default text on focus. Ignore user-inserted text
function removeText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal == defVal) {
            thisObj.attr("value", "");
            thisObj.removeClass("empty")
        }
    }
}

// Restore default text on focus. Ignore user-inserted text
function restoreText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal != undefined && currVal != '') {
            thisObj.attr("value", currVal);
        }
        else if (currVal == undefined || currVal == '') {
            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}


function loadGoogleMapApi() {
    google.load("maps", "2", { "callback": initMap });
}

function initMap() {

    var firstHtml = "<h3>Lewisham College</h3><p>Lewisham Way, London SE4 1UT</p>";
    var secHtml = "<h3>Deptford Campus</h3><p>2 Deptford Church Street, London SE8 4RZ</p>";
    var map = new GMap2($(".googleMap").get(0));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setMapType(G_NORMAL_MAP);
    map.enableContinuousZoom();
    map.setCenter(new google.maps.LatLng(51.468218, -0.025942), 16);
    var firstPoint = new GLatLng(51.468218, -0.025942);
    var secPoint = new GLatLng(51.4753135, -0.0234582);
    var mapCentre = new GLatLng(51.4717931, -0.0237908);
    var secIcon = new GIcon(G_DEFAULT_ICON);
    secIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    secIcon.iconSize = new GSize(32, 32);
    
    var firstMarker = new GMarker(firstPoint, new GIcon(G_DEFAULT_ICON));
    var secMarker = new GMarker(secPoint, secIcon);
    map.setCenter(mapCentre, 15);
    map.addOverlay(firstMarker);
    map.addOverlay(secMarker);

    

    GEvent.addListener(firstMarker, "click", function() {
        firstMarker.openInfoWindowHtml(firstHtml);
    });

    GEvent.addListener(secMarker, "click", function() {
        secMarker.openInfoWindowHtml(secHtml);
    });

}

function checkErrors() {
    if ($("#mainContent fieldset .error:visible").length = 0) {
        alert("hello");
        var buttonError = document.createElement("span");
        $(buttonError).addClass("globalError").text("Please check all required fields are complete");

        $(".applyConf .button").append(buttonError);

    }
    
    else {

        $(".applyConf .button .globalError").remove();
    }
}

function checkInterests() {

    var checkCount =  $(".interests table input:checked");
    
    if (checkCount.length > 0){
        return true;
    }
    else {
        return false;
    }
}

function googlePageLoad()
{
// turned off for now. Gives the final dom load time as a google event. Easier to deploy if in this file.
//	$(function() {
//		try {
//			pageTracker._trackEvent("Page load", "Load time", location.pathname, (new Date()).valueOf() - pageLoadTime.valueOf());
//		}
//		catch (err) {}
//	});
}

