$(document).ready(function(){
    var cmpName = $("#campus-name"),
        cmpList = $("#campus-select").find(".campus-list");
    cmpName.click(function(){
        cmpList.toggle(0,function(){
            if(cmpName.find(".arrow").hasClass("open")){
                cmpName.find(".arrow").removeClass("open");
            }else{
                cmpName.find(".arrow").addClass("open");
            }
        });
    });
    var ck = {
		setCookie:function (name, value, days) {
			if (typeof(days) != 'undefined') {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires=" + date.toGMTString();
			}else {
				var expires = "";
			}
			document.cookie = name+"="+value+expires+"; path=/";
		},
	   getCookie:function (name) {
			name = name + "=";
			var carray = document.cookie.split(';');

			for(var i=0;i < carray.length;i++) {
				var c = carray[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
			}
			return null;
		},
		deleteCookie :function (name) {
			this.setCookie(name, "", -1);
		}
	}
	
    function parseURL(url) {
        var a =  document.createElement('a');
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(':',''),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function(){
                var ret = {},
                    seg = a.search.replace(/^\?/,'').split('&'),
                    len = seg.length, i = 0, s;
                for (;i<len;i++) {
                    if (!seg[i]) { continue; }
                    s = seg[i].split('=');
                    ret[s[0]] = s[1];
                }
                return ret;
            })(),
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
            hash: a.hash.replace('#',''),
            path: a.pathname.replace(/^([^\/])/,'/$1'),
            relative: (a.href.match(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
            segments: a.pathname.replace(/^\//,'').split('/')
        };
    }
    
    //console.log(parseURL(window.location));
    var parsedurl = parseURL(window.location);

    if(Modernizr.touch){
        $(".campus").not(".comingsoon").bind("touchend",function(e){
            if($(this).hasClass('over')){
                if($(this).hasClass("onlinelink")){
                    window.location = $(this).find(".imgwrap a").attr("href");
                }else{
                    var campus = $(this).attr("data-slug");
                    parsedurl.segments[0] = campus;
                    
                    var path = parsedurl.segments.join("/");
                    
                    ck.setCookie("campus",campus,2000);
                    window.location = "http://"+parsedurl.host+"/"+path;
                }
                $(this).removeClass('over');
            }else{
                $(this).addClass('over');
            }
            e.preventDefault();
        });
    }else{
        //go to campus selected and set cookie
        $(".campus").not(".comingsoon").find(".campuslink").click(function(e){
            if($(this).parent().hasClass("onlinelink")){
                window.location = $(this).find(".imgwrap a").attr("href");
            }else{
                var campus = $(this).parent().attr("data-slug");
                parsedurl.segments[0] = campus;
                
                var path = parsedurl.segments.join("/");
                
                ck.setCookie("campus",campus, 2000);
                window.location = "http://"+parsedurl.host+"/"+path;
            }
            e.preventDefault();
        });
    }

    //object with methods to hide or show live or ondemand content
    eventlive = {
      live : function(){
        if($("body").hasClass("online")){
          //console.log("making live");
          $(".online-content").addClass("hide");
          $(".onlive").removeClass("hide");
          $(".ondemand").addClass("hide");
        }
      },
      offline :function(){
        if($("body").hasClass("online") && today != 0){
            //console.log("it is offline");
            $(".online-content").addClass("hide");
            $(".onlive").addClass("hide");
            $(".ondemand").removeClass("hide");    
        }
      },
      prelive: function(periods){
        if($("body").hasClass("online")){
            //if($.countdown.periodsToSeconds(periods) <= 900){ 
               //console.log("it is live");
               $(".online-content").addClass("hide");
               $(".onlive").removeClass("hide");
               $(".ondemand").addClass("hide");
            //}
        }
      }
    }
    function initCountdown(){
        var idx = 0;
        var ndx = 0;
        $.getJSON("/_inc/countdown-times.php",function(data){
            //console.log(data[idx]);
            
           /*function setEastTimeZone(){
                var d = new Date();
                localTime = d.getTime();
                localOffset = d.getTimezoneOffset() * 60000;
                utc = localTime + localOffset;
                offset = -4;
                eastCoast = utc +(360000*offset);
                
                return eastCoast;
            }*/
            
            var starttime = new Date(data[idx].date.start),
                endtime = new Date(data[idx].date.end),
                curtime = new Date(),
                today = curtime.getDay(),
                lbs = ["YR","MO", "WK", "days","hours","minutes","seconds"],
                smlbs = ["yrs","mo", "wk", "d","hr","min","sec"],
                layout = "{dn}<span>{dl}</span> {hn}<span>{hl}</span> {mn}<span>{ml}</span> {sn}<span>{sl}</span>",
                livelayout = "{desc}",
                live = {until:endtime, format:'DHMS', onExpiry:setNext, description:"<span class='livelink'><a href='/online'>Service Is Live</a></span>",timezone:-4,labels:lbs,labels1:lbs,layout:livelayout},
                smlive = {until:endtime, format:'DHMS', description:"<span class='livelink'><a href='/online'>Service Is Live</a></span>",timezone:-4,labels:smlbs,labels1:smlbs,layout:livelayout},
                notlive = {until:starttime, format:'DHMS', onExpiry:setNext,labels:lbs,timezone:-4,labels1:lbs,layout:layout}, //onTick:eventlive.prelive
                smnotlive = {until:starttime, format:'DHMS',labels:smlbs,timezone:-4,labels1:smlbs,layout:layout},
                csmall = $("#cntsml"),
                clarge = $("#cntlg");
            
            function log(){
                console.log("-----------------------------------------------------------");
                console.log("CURTIME:   "+ curtime);
                console.log("STARTTIME: "+ starttime);
                console.log("ENDTIME:   "+ endtime);
                console.log("-----------------------------------------------------------");
            }
    
            //log();
            //console.log("countdown started");
            //accounts for events in data that have already happened or are happening
            if(curtime < endtime && curtime > starttime){
                clarge.countdown({until:endtime, format:'DHMS',onExpiry:setNext, description:"<span class='livelink'><a href='/online'>Service Is Live</a></span>",labels:lbs,labels1:lbs,layout:livelayout});
                csmall.countdown({until:endtime, format:'DHMS', description:"<span class='livelink'><a href='/online'>Service Is Live</a></span>",labels:smlbs,labels1:smlbs,layout:livelayout});
                eventlive.live();
                //console.log("live");
                ndx = ndx + 1;
                starttime = new Date(data[ndx].date.start);
            }else if(curtime > endtime){
                //accounts for multiple times that may have expired gets next online service.
                for(var i = 0; i < data.length; i++){
                    ndx = ndx + 1;
                    //setNext();
                    starttime = new Date(data[ndx].date.start);
                    if(curtime < starttime){
                        break;
                    }
                }
                //log();
                //console.log(starttime);
                //console.log(data[n].date.start);
                //window.console.log("NOT LIVE 1");
                $("#cntlg").countdown({until:starttime, format:'DHMS', onExpiry:setNext,labels:lbs,labels1:lbs,layout:layout});
                $("#cntsml").countdown({until:starttime, format:'DHMS',labels:smlbs,labels1:smlbs,layout:layout});
                //console.log("offline");
                //eventlive.offline(); 
                eventlive.prelive(); 
            }else{
                starttime = new Date(data[ndx].date.start);
                //console.log("STARTTIME: "+ starttime);
                $("#cntlg").countdown({until:starttime, format:'DHMS', onExpiry:setNext,labels:lbs,labels1:lbs,layout:layout});
                $("#cntsml").countdown({until:starttime, format:'DHMS',labels:smlbs,labels1:smlbs,layout:layout});
               // window.console.log("NOT LIVE 2");
                //eventlive.offline();
                eventlive.prelive();
            }
            
             function setNext(){
                 if(ndx===idx){
                     $("#cntlg").countdown('change',{until:endtime, format:'DHMS', onExpiry:setNext, description:"<span class='livelink'><a href='/online'>Service Is Live</a></span>",labels:lbs,labels1:lbs,layout:livelayout});
                     $("#cntsml").countdown('change',{until:endtime, format:'DHMS', description:"<span class='livelink'><a href='/online'>Service Is Live</a></span>",labels:smlbs,labels1:smlbs,layout:livelayout});
                     eventlive.live();
                     //console.log("LIVE 2");
                     ndx = ndx + 1;
                     starttime = new Date(data[ndx].date.start); 
                 }else{
                    notlive.description = "";
                    smnotlive.description = "";
    
                    //window.console.log("NOT LIVE 3");
                    starttime = new Date(data[ndx].date.start);
                    idx = ndx;
                    $("#cntlg").countdown('change',{until:starttime, format:'DHMS', onExpiry:setNext,labels:lbs,labels1:lbs,layout:layout});
                    $("#cntsml").countdown('change',{until:starttime, format:'DHMS',labels:smlbs,labels1:smlbs,layout:layout});
                    //eventlive.offline();
                    eventlive.prelive();
                    //log();
                 }
             }
             //if today is Sunday show live service content
             /*if(today === 0 || today === starttime.getDay()){  
                 eventlive.prelive();
             }*/
             
             eventlive.prelive(); 
             
             if($("body").hasClass("online")){
                 if(parsedurl.params.sls === "1"){
                     clarge.countdown('pause');
                     csmall.countdown('pause');
                     eventlive.live();
                 }
             }
        });
    }
    
    initCountdown();
    
    $(".griditem").parent().addClass(".gridwrap");
    $(".griditem:nth-child(3n)").addClass('end');
    
    
    $('.login .thickbox, #comments .thickbox').colorbox({iframe:true,width:400, height:250});
    $('#footer .thickbox').colorbox();
    $('.slideshow').colorbox({
    	slideshow:true,
    	photo:true,
    	preloading:true,
    	slideshowSpeed:5000,
    	slideshowAuto:false
    	});
    $('.rsvp .thickbox, #subnav .thickbox').colorbox({iframe:true,width:450, height:570});
    $('#options .thickbox,.section .thickbox').colorbox({iframe:true,width:500, height:570});
    //colorbox for campus map btn
    $('.map.thickbox').each(function(){
        var lat = $(this).attr("data-lat");
        var lon = $(this).attr("data-lon");
        $(this).colorbox({
            iframe:true,
            width:500, 
            height:500,
            top:"0px",
            href:"/_inc/gmap.php?lat="+lat+"&lon="+lon
        });
    });
    
    $("#footerlinks").find(".sep:last").addClass("last");
    // change last line separator depending on amount of links
    var footerwidth = 976;
    var subwidth = 0;
    $("#footerlinks").find("li").each(function(){
        if($(this).hasClass("last")){}else{
          subwidth += $(this).outerWidth(true);
        }
    });
    var sepwidth = (footerwidth - subwidth) - 5;
    $("#footerlinks").find(".last").css({"width": sepwidth+"px"});
    
    $(".togglecontent").hide();
    if($(".toggle").length > 0){
        var exp = $(".toggle");
        exp.prepend("<div class='arrow'></div>");
        exp.click(function(e){
            $(this).toggleClass("open");
            $(this).next('.togglecontent').toggle();
            e.preventDefault();
        });
    }
    
    $("#countdown-wrap").click(function(){
        window.location = "/online";
    });
    
    if($(".dayevent").length > 0){
        $(".dayevent").each(function(){
            if($(this).next().hasClass("day")){
                $(this).css({"border-bottom":"none"});
            }
        });
    }
    
    if($(".monkForm").length > 0){
        $(".monkForm").find("legend:first").remove();
    }
    
    
    /*$.extend($.expr[':'], {
        whitespace: function(el) {
            return $(el).text().search(/\s+/);
        }
    });*/
    
    //below applied due to biltmores windows machines having Helvetica installed
    //With helvetica installed on windows swaps characters where &nbsp; characters are.
    
    var pgr = document.getElementsByTagName("p");
    var tdr = document.getElementsByTagName("td");
    
    for(var i=0; i< pgr.length ; i++){
        var p = $(pgr[i]);
        if(p.html() === "&nbsp;"){
            p.css({"font-family":"sans-serif"});
        }
    }
    for(var i=0; i< tdr.length ; i++){
        var td = $(tdr[i]);
        if(td.html() === "&nbsp;"){
            td.css({"font-family":"sans-serif"});
        }
    }
    
});


