﻿/*

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() {

    loadTwitterFeed(writeTwitterFeed);

    // 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 .selectedInterests tr:nth-child(odd)").addClass("odd");


    ///////////////////////////////////
    // Application Validation Method //
    ///////////////////////////////////

    $(".applyConf .button input").click(function() {

        //checkErrors();


    });


    ///////////////////////////////////////////
    // Application Form Schools Autocomplete //
    ///////////////////////////////////////////

    $("fieldset .eduName input").focus(function() {
        var autocompleteFields = $("fieldset .eduName input");

        if (autocompleteFields.length > 0) {
            $.getScript("/scripts/localData.js", function() {

                autocompleteFields.autocomplete(schoolsList, {
                    delay: 100,
                    minChars: 2,
                    matchSubset: 1,
                    matchContains: 1,
                    cacheLength: 100,
                    scroll: true,
                    selectFirst: false,
                    autoFill: false
                });
            });
        }
    });



    /////////////////////////////////////////////
    // Application Form Languages Autocomplete //
    /////////////////////////////////////////////

    $("fieldset .firstLanguage input").focus(function() {

        var autocompleteLangFields = $("fieldset .firstLanguage input");

        if (autocompleteLangFields.length > 0) {
            $.getScript("/scripts/localData.js", function() {

                autocompleteLangFields.autocomplete(languagesList, {
                    delay: 100,
                    minChars: 2,
                    matchSubset: 1,
                    matchContains: 1,
                    cacheLength: 100,
                    scroll: true,
                    selectFirst: false,
                    autoFill: false
                });
            });
        }
    });




    ///////////////////////////////
    // 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() {
        var selected = false;
        var tab = location.querystring["tab"];
        $(this).contents().find("li").each(function(e) {
            if ((tab == "" && e < 1) || e == tab-1) {
                $(this).addClass("selected");
                selected = true;
            }
        });
        if (!selected) {
            $(this).contents().find("li").eq(0).addClass("selected");
        }
    });

    $(".tablet").each(function() {
        var tab = location.querystring["tab"];
        var selected = false;
        $(this).contents().find(".section").each(function(e) {
            $(this).hide();
            if ((tab == "" && e < 1) || e == tab-1) {
                $(this).show();
                selected = true;
                $('html,body').animate({ scrollTop: $(".tablet").offset().top-50 }, { duration: 'slow', easing: 'swing' })
            }
        });
        if (!selected) {
            $(this).contents().find(".section").eq(0).show();
        }
    });

    // 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 = "https://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) {
        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 validateSupportCheck(sender, args) {
    var supportSection = $(".applySupp");
    var checkSupport = $(".supportCheck input:checked");
    if (checkSupport.length > 0) {
        args.IsValid = true;
    }
    else {
        args.IsValid = false;
        supportSection.focus();
    }
}


function validateFindAddressClick(sender, args) {

    var addressInput = $("#addressFieldShown");
    var postcodeRadio = $(".postcodeRadio");

    if (addressInput.length > 0) {
        args.IsValid = true;
    }
    else {
        postcodeRadio.focus();
        args.IsValid = false;
    }

}

function validateSupportRequiredField(sender, args) {
    var supportSection = $(".applySupp");
    var checkSupport = $(".supportCheck input:checked");
    var textSupport = $(".suppMed textarea");
    var boolValid = true;

    if (checkSupport.val() == '1') {

        if (textSupport.val().trim() == '') {
            boolValid = false;
            supportSection.focus();
        }
    }

    args.IsValid = boolValid;
}

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) {}
    //	});
}

//////////////////////////////////////////////////////////////////////////
// Load the Twitter Feed using YQL and Cross Domain compatible callback //
//////////////////////////////////////////////////////////////////////////
function loadTwitterFeed(callback) {

    // Take the provided url, and add it to a YQL query. Make sure you encode it!
    var yql = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20twitter.user.timeline%20where%20screen_name%3D'lewishamcollege'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?";

    // Request that YSQL string, and run a callback function.
    // Pass a defined function to prevent cache-busting.
    $.getJSON(yql, cbFunc);

    function cbFunc(data) {
        // If we have something to work with...
        if (data.query) {
            // If the user passed a callback, and it
            // is a function, call it, and send through the data var.
            if (typeof callback === 'function') {
                callback(data);
            }
        }
        // Else, Maybe we requested a site that doesn't exist, and nothing returned.
        else throw new Error('Nothing returned from getJSON.');
    }
}

function writeTwitterFeed(data)
{
    var twitterContainer = $(".twitterFeed ul");
    var numberOfStatuses = $(".twitterFeed ul").attr("data-numberOfStatuses");
    if (!twitterContainer.length ) {
        return;
    }
    var i;

    var feed = [];

    for (i = 0; i < numberOfStatuses && i < data.query.results.statuses.status.length; i++) {
        var date = parseDate(data.query.results.statuses.status[i].created_at);
        feed.push('<li><p>' + ConvertLinks(data.query.results.statuses.status[i].text) + ' <a href="http://www.twitter.com/lewishamcollege/status/' + data.query.results.statuses.status[i].id + '">#</a> ' +
        dateToString(date) + '</p></li>');
    }
    twitterContainer.append(feed.join(""));
}

//////////////////////////////////////////////
// Convert urls in a block of text to links //
//////////////////////////////////////////////
function ConvertLinks(text) {
    if (!text) return text;

    text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi, function(url) {
        nice = url;
        if (url.match('^https?:\/\/')) {
            nice = nice.replace(/^https?:\/\//i, '')
        }
        else
            url = 'http://' + url;


        return '<a target="_blank" rel="nofollow" href="' + url + '">' + nice.replace(/^www./i, '') + '</a>';
    });

    return text;
}

location.querystring = (function() {

    // The return is a collection of key/value pairs
    var queryStringDictionary = {};

    // Gets the query string, starts with '?'
    var querystring = decodeURI(location.search);

    // document.location.search is empty if no query string
    if (!querystring) {
        return {};
    }

    // Remove the '?' via substring(1)
    querystring = querystring.substring(1);

    // '&' seperates key/value pairs
    var pairs = querystring.split("&");

    // Load the key/values of the return collection
    for (var i = 0; i < pairs.length; i++) {
        var keyValuePair = pairs[i].split("=");
        queryStringDictionary[keyValuePair[0]]
                = keyValuePair[1];
    }

    // toString() returns the key/value pairs concatenated
    queryStringDictionary.toString = function() {
        if (queryStringDictionary.length == 0) {
            return "";
        }
        var toString = "?";
        for (var key in queryStringDictionary) {
            toString += key + "=" +
                queryStringDictionary[key];
        }
        return toString;
    };
    // Return the key/value dictionary
    return queryStringDictionary;
})();

function dateToString() {
    var d, m, y;
    var delimiter = "/";
    var date = null;
    if (arguments.length <= 2) {
        date = new Date(arguments[0]);

        if (arguments[1]) delimiter = arguments[1];
    }
    else {
        date = new Date(arguments[2], arguments[1] - 1, arguments[0]);
        if (arguments[3]) delimiter = arguments[3];
    }

    d = date.getDate();
    m = date.getMonth() + 1;
    y = date.getFullYear();

    return ("0" + d).slice(-2) + delimiter + ("0" + m).slice(-2) + delimiter + y;
}

function parseDate(str) {
    var v = str.split(' ');
    return new Date(Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3] + " UTC"));
} 
