/*

	Filename             sitewide.js
	Detail               Site functionality
	Author:              thunder::tech inc.
	License:             CLIENT is defined as the owner of online property from which this file resides or this code is referenced in.
						 ADDITIONAL PARTY is defined as anyone other than thunder::tech or CLIENT.
						 No right is granted to ADDITIONAL PARTY to sell, distribute, modify or otherwise transfer the following source code without explicit written permission by CLIENT or thunder::tech.

*/

/*  ================================
     Sitewide JavaScript
    ================================ */

var Project = {};

Project.pageLoaded = function () {
    //thunder.client.project.flashReplace();
    //thunder.client.modify.rollImages();
    //thunder.client.modify.linkOptions();
    //thunder.client.modify.tabSet();

    //thunder.client.modify.treeMenu(false, [thunder.client.modes.separatorTreeMenu]);
    //thunder.client.modify.treeMenu(false, [thunder.client.modes.imageTreeMenu]);
    thunder.client.modify.selfLabelFields();
    //thunder.client.modify.requireFields();
    //thunder.client.modify.dropSelector(true);
    //thunder.client.modify.scrollFeature(640, 3000, 500);
    thunder.client.workarounds.alphaImages();
    thunder.client.workarounds.labelAsBrowser();


    //home logo scroller
    if ($(".slider li").length > 3) {
        $('.slider').scrollIt({
            menuHeight: 134,
            menuWidth: 525,
            itemHeight: 128,
            itemWidth: 172,
            itemMargin: 3
        });
    }

    $(".events .event:last").css("border", "none");

    $(".mailinglist").click(function () { $(".mailPopup").css("display", "block"); $(".mailPopup").stop(true, false).animate({ opacity: 1 }, 250); });
    $(".close").click(function () {
        $(".mailPopup").stop(true, false).animate({ opacity: 0 }, 250, function () {
            $(".mailPopup").css("display", "none");
        });
    });
    $(".mailPopup, .rollover").css("opacity", "0");

    var offset;
    $(window).load(function () {

        $(".project-sub .thunder-menu > .menu-item").each(function () {
            if ($(this).is('.news, .engage, .services')) {
                offset = $(this).outerWidth();
                offset = ((offset - $(".menu-dropdown", this).outerWidth()) / 2) + 10;
                $(".menu-dropdown", this).css("left", Math.round(offset) + "px");

            }
        });

        $(".project-home .thunder-menu > .menu-item").each(function () {
            $("a img:first", this).data("origHeight", $(this).height());
            $(".rollover", this).data("origHeight", $(this).height());
        });

        $(".menu-ddbubble").each(function () {
            offset = $(this).height();
            offset = ((offset - $(".menu-item:last", this).position().top) / 2) - 10;
            $(this).css("padding-top", Math.round(offset) + "px").css('height', $(this).height() - Math.round(offset) + "px");
            $(this).css("display", "none");
        });

        thunder.client.modify.treeMenu(false);

        $(".blueBox .update").each(function () {
            offset = $(this).height();
            offset = ((offset - $("p", this).height()) / 2) - 2;
            $("p", this).css("top", Math.round(offset) + "px");
        });

        $(".blueBox > div").css("display", "none");
        $(".blueBox > div:first").css("display", "block");
        $(".icon-facebook").mouseover(function () { showChannel("facebook"); }).addClass("active");
        $(".icon-twitter").mouseover(function () { showChannel("twitter"); });
        $(".icon-youtube").mouseover(function () { showChannel("youtube"); });
    });


    $(".project-home .rollover").css({ opacity: 0 });


    //footer vendor logos
    var numOfGroups = Math.ceil($(".vendors a").size() / 3);
    for (i = 0; i < numOfGroups; i++) {
        $(".vendors a").slice(i * 3, (i + 1) * 3).wrapAll("<div></div>");
    }
    $('.vendors .container').cycle({ fx: 'fade', speed: 1000, timeout: 6000 });

    //calendar functionality
    if ($(".calendar").length > 0) {

        $(".calendar .event").each(function () {
            offset = $(this).height();
            offset = ((offset - $("p", this).height()) / 2);
            $("p", this).css("top", Math.round(offset) + "px");
        });

        $(".viewMore a").click(function () {
            $(".viewMore a").removeClass("active");
            $(this).addClass("active");
            syncCalendar();
        });
        $(".months a").mouseenter(function () {
            $(".months a").removeClass("active");
            $(this).addClass("active");
            syncCalendar();
        });

        syncCalendar();
    }





    $(".footerNavLogos a:last").css("margin", "0");
    $(".leftNav a:last").css("border", "none");




    fbFetch();
}

function showChannel(social) {
    $(".blueBox > div").css("display", "none");
    $(".social-buttons a").removeClass("active");
    $(".cont-" + social).css("display", "block");
    $(".icon-" + social).addClass("active");

    $(".blueBox .update").each(function () {
        offset = $(this).height();
        offset = ((offset - $("p", this).height()) / 2) - 2;
        $("p", this).css("top", Math.round(offset) + "px");
    });
}

function fbFetch(){
    var requestURL = 'https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=188845277831797&client_secret=1dfd33c5b5ac2bc173e5541f1309e018'; //calback=? is required to get JSONP behaviour
    var fbMsg, postid, token, count, access_token, img;

    /*$.get(requestURL, function (data) {
        alert(data);
		eval(data);
    });*/
    
    requestURL = 'https://graph.facebook.com/128203721108/posts?limit=5&access_token=188845277831797|wi-eguUQDhNjyfg7koSnJJyBp0I&callback=?'; //calback=? is required to get JSONP behaviour
    $.getJSON(requestURL, function (json) {

        $.each(json.data, function (i, fb) {
            fbMsg = fb.message;
            img = fb.icon;
            postid = fb.id.substr(fb.id.indexOf("_") + 1);
            if (fb.message.length > 110) {

                fbMsg = fbMsg.substr(0, 110);
                fbMsg = fbMsg.substr(0, fbMsg.lastIndexOf(" "));
            }

            ///themes/redesign2011/images/fbicon-gcsc.jpg
            $(".blueBox .cont-facebook").append("<div class='update'><img src='http://graph.facebook.com/clesports/picture' /><p><strong>Cleveland Sports Commission:</strong> " + fbMsg + "... <a target='_blank' href='http://www.facebook.com/clesports/posts/" + postid + "' >[read more]</a></p></div>");
            // alert("<li>" + fb.message + "</li>");
        });
    });

    //blueBox layout corrections
    $(".blueBox .update:odd").css("background", "#00478E");
    $(".blueBox .update:last").css("border", "none");

    
}

function syncCalendar(){
	var year = $(".viewMore .active").html();
	var month = $(".months .active").html().toLowerCase();
	
	$(".calendar .event, .noEvents").css("display", "none");
	if ($('.' + year + month).length > 0) {
		$('.'+year+month).css("display", "block");
    } else {
		$(".noEvents").css("display", "block");
	}
	
}

function loadTwitterStatusTimeline(obj, handle) {
	var itemText;
	var tempDate;
	if (handle != undefined){
	    $.ajax({
	        type: "GET",
	        url: "/themes/redesign2011/scripts/twitterhandler.ashx?action=getStatusTimeline&username=" + handle,
	        dataType: "xml",
	        success: function (xml) {
	            var profileImg = $(xml).find('profile_image_url:eq(0)').text();

	            $(xml).find('status').each(function (i, status) {

	                var text = $(status).find("text:eq(0)").text();
	                var wtf = $(status).find("created_at:eq(0)").text();


	                if ($.browser.msie) {
	                    // IE can't parse these crazy Ruby dates
	                    tempDate = Date.parse(wtf.replace(/( \+)/, ' UTC$1'));
	                    tempDate = new Date(tempDate);
	                } else { tempDate = new Date(wtf); }

	                itemText = text.replace(/(https?:\/\/\S+)/gi, function (s) {
	                    var s2;
	                    if (s.length >= 40) { //IE7 will otherwise put the whole link on one line, no matter what CSS you put
	                        var temp1, temp2;
	                        temp1 = s.substr(0, 39);
	                        temp2 = s.substr(39, s.length);
	                        s2 = temp1 + "<br>" + temp2;
	                    } else {
	                        s2 = s
	                    }
	                    return '<a target="_blank" href="' + s + '">' + s2 + '</a>';
	                });
	                $(obj).append('<li>' + itemText + ' <span class="bullet">&bull;</span></li>');
	                $(obj).append();
	                $(".cont-twitter").append("<div class='update'><img src='" + profileImg + "' /><p><strong>Cleveland Sports Commission:</strong> " + itemText + "</p></div>")

	            });
	            $(".bullet:last", obj).remove();

	            $("#listticker").liScroll({ travelocity: .04 });
	        },
	        error: function () { $(obj).html('<li>Error loading twitter feed.</li>'); }
	    }); 
		
		
	}
	else {
		$(obj).html('<li>Nothing to look at here...move along.</li>');
	}  
}




/*!
 * liScroll 1.0
 * Examples and documentation at: 
 * http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html
 * 2007-2010 Gian Carlo Mingati
 * Version: 1.0.2.1 (22-APRIL-2011)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires:
 * jQuery v1.2.x or later
 * 
 */


jQuery.fn.liScroll = function (settings) {
    settings = jQuery.extend({
        travelocity: 0.07
    }, settings);
    return this.each(function () {
        var $strip = jQuery(this);
        $strip.addClass("newsticker")
        var stripWidth = 0;
        $strip.find("li").each(function (i) {
            //stripWidth += $(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
            if ($.client.os != 'Mac') { stripWidth += $(this, i).outerWidth(true); }
            else { stripWidth += Math.ceil(parseFloat(window.getComputedStyle($(this, i).get(0), "").getPropertyValue("width"))); }
            if (test != "") { alert(Math.ceil(parseFloat(window.getComputedStyle($(this, i).get(0), "").getPropertyValue("width")))); }
        });
        var $mask = $strip.wrap("<div class='mask'></div>");
        var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
        var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width 	



        $strip.width(stripWidth);
        var totalTravel = stripWidth + containerWidth;
        var defTiming = totalTravel / settings.travelocity; // thanks to Scott Waye		
        function scrollnews(spazio, tempo) {
            $strip.animate({ left: '-=' + spazio }, tempo, "linear", function () { $strip.css("left", containerWidth); scrollnews(totalTravel, defTiming); });
        }
        scrollnews(totalTravel, defTiming);

        $strip.hover(function () {
            jQuery(this).stop();
        },
				function () {
				    var offset = jQuery(this).offset();
				    var residualSpace = offset.left + stripWidth;
				    var residualTime = residualSpace / settings.travelocity;
				    scrollnews(residualSpace, residualTime);
				});
    });
};

$(Project.pageLoaded);
