var channel = geChannelName();
$(document).ready(function() {

    // channel according to path or content

    if (channel == "default" || channel == "about") {
        if (document.getElementById("tweetcontainer")) {
            prepareTwitter();
        }

        if (document.getElementById('flickrHome')) {
            init();
            flickrController();
        }


        // loop homeSponsor
        $("#homeSponsor a,.animate a").hide();
        loopLinks($("#homeSponsor"), 5000);
        loopLinks($(".animate"), 4500);

        // check query string, fire when from email
        var s = window.location.search.substring(1).split("&");

        if (s.length > 0) {

            for (x = 0; x < s.length; x++) {
                var b = s[x].split("=");

                if (b[0] == "tu") {
                    if (b[1] == "b") {
                        // fire send to boss tag
                        FireTrack("Tell my boss", "default.aspx", "Email Link: Tell my boss");
                    } else if (b[1] == "f") {
                        // fire send to friend
                        FireTrack("Spread Word", "default.aspx", "Email Link: Email Friend");
                    }
                }
            }

        }
    }
    if (channel == "agenda") {
        $("#agendaDayUL li:first").addClass("active");
        $("#agendaDayUL tr:even").addClass("altRow");

        $(".dayBank a.day:first").addClass("selected");

        $(".dayBank a.day").click(function() {
            // get index from day attr, hide all uls, show index
            var i = $(this).attr("day");
            $("#agendaDayUL li.active").removeClass("active");
            $("#agendaDayUL li:nth-child(" + i + ")").addClass("active");
            // change selected day
            $(".dayBank a.selected").removeClass("selected");
            $(this).addClass("selected");

        });

        // show all
        $("a.showall").click(function() {
            $(".dayBank").hide();
            $(".dayview").show();
            $(".dayBank a.day").removeClass("selected");
            $("#agendaDayUL").removeClass("agendaDays").addClass("agendaDaysAll");
            $("#agendaDayUL li").addClass("active").addClass("viewall");
        });

        // show by day
        $(".dayview a").click(function() {
            $(".dayBank").show();
            $(".dayview").hide();
            $("#agendaDayUL").removeClass("agendaDaysAll").addClass("agendaDays");
            $("#agendaDayUL li").removeClass("active").removeClass("viewall");
            $(".dayBank a.day:first").addClass("selected");
            $("#agendaDayUL li:first").addClass("active");


        });

    }

    // for all dls under dynamicdl, animate on request
    if (document.getElementById("dynamicdl")) {
        prepareDynamicList();
    }
    if (channel == "tracks") {
        prepareTechnicalTracks("tracks");

    }

    if (channel == "preconference-agenda") {
        prepareTechnicalTracks("tracks");
        prepareTechnicalTracks("tracks1");
        prepareTechnicalTracks("tracks2");
        prepareTechnicalTracks("tracks3");
    }

    if (channel == "free-sessions") {
        prepareTechnicalTracks("tracks1");
    }

    if (channel == "spread_word") {
        spreadWordPage();
    }

    if (channel == "travel_and_hotels") {
        loadMyMap();
    }

    if (channel == "social") {
        doFlickr('flickrcontainer');
        if (document.getElementById('twitterConnect')) {
            twttr.anywhere(function(T) {
                T("#follow-placeholder").followButton('auteched');
            });
            var PageTweets = new TechedTweet();
            PageTweets.Init("lifetweets");
        }
        if (document.getElementById('rssConnect')) {
            rssConnect();
        }


    }
});

function geChannelName() {
    var pathname = location.pathname;
    pathname = pathname.substring(pathname.lastIndexOf("/") + 1);
    if (pathname.indexOf(".") > -1) {
        pathname = pathname.split(".")[0];
    }
    if (pathname.indexOf("?") > -1) {
        pathname = pathname.split("?")[0];
    }
    if (pathname.indexOf("#") > -1) {
        pathname = pathname.split("#")[0];
    }
    if (pathname == "") pathname = "default";
    return pathname.toLowerCase();
}
function FireTrack(s0, s1, s2) {
    // s0: action name e.g. tell my boss, s1: url e.g. spread_word, s2: tag value e.g. "Link: Register for TechEd Australia 2010"
    // according to input, call function

    if (typeof (dcsMultiTrack) == "function") {
        var str = String("dcsMultiTrack('WT.z_locale','en-au','WT.z_ea_actionoffer','Shr-Lev','WT.z_ea_name','{0}::Aud:IT-Pro::CLKFALSE','WT.z_ea_targetcampaign','103LAU10222','WT.dl','1','DCS.dcssip','australia.msteched.com','DCS.dcsuri','','DCSext.wtEvtSrc','australia.msteched.com/{1}','WT.ti','Link: {2}');").replace("{0}", s0).replace("{1}", s1).replace("{2}", s2);
        eval(str);

    }

}
function prepareTwitter() {
    //var url = "http://search.twitter.com/search.json?q=auteched&callback=?";
    var url = "http://search.twitter.com/search.json?lang=en&rpp=5&show_user=true&q=%23auteched&result_type=mixed&callback=?";
    // geocode=40.757929%2C-73.985506%2C25km 
    var tweets = $('<ul id="autweets">').appendTo("#tweetcontainer");

    $.getJSON(url, function(data) {
        $.each(data.results, function(i, item) {
            //  tweets.append('<li><img src="' + item.profile_image_url + '" alt="' + item.from_user + '" /><a href="http://twitter.com/' + item.from_user + '/statuses/' + item.id + '" title="@'+item.from_user +'"> <strong>@' + item.from_user + '</strong></a>: ' + item.text + '</li>');
            tweets.append(('<li><img src="{0}" alt="{1}" /><strong>{2}</strong>:{3}</li>').replace("{0}", item.profile_image_url).replace("{1}", item.from_user).replace("{2}", item.from_user).replace("{3}", item.text));
        });
    });
}
function loopLinks(o, t) {
    o.find("a:hidden:first").fadeIn("slow");
    //setInterval(function() {
    //    var onext = o.find("a:hidden:first");
    //    o.find("a:visible").fadeOut("fast", function() {
    //        onext.fadeIn("fast");
    //    });
    //}, t);
    setInterval(function() {
        var onext = o.find("a:visible:first").next();
        if (onext.attr("id") == undefined) {
            onext = o.find("a:first");
        }
        o.find("a:visible").fadeOut("fast", function() {
            onext.fadeIn("fast");
        });
    }, t);
}
function prepareDynamicList() {
    $("#dynamicdl dt").toggle(function() {
        $(this).next("dd").slideDown("fast", "jswing");
    }, function() {
        $(this).next("dd").slideUp("fast", "jswing");
    });


}

function prepareTechnicalTracks(id) {
    // hide all divs, show when requested
    var t = $("#" + id);

    var h = t.find(".trackslist").height();


    if (t.find(".tracksdetails").is(":visible")) {
        t.find(".tracksdetails").css("min-height", h - 40);
    } else {
        t.find(".tracksdetails").css("min-height", 300);

    }

    t.find(".trackslist li").click(function() {
        // get id from tab id, find visible in trackitem, hide and show new one
        t.find(".trackitem:visible").hide();
        t.find(".trackslist li.active").removeClass("active");
        $("#" + $(this).attr("tabid")).show();
        $(this).addClass("active");
    });

    // if # in url, show hide accordingly
    var page = location.hash;
    if (page != "") {
        // find id and show

        $.each(t.find(".trackslist li"), function() {
            if ("#" + $(this).attr("tabid") == page) {
                $(this).click();
                // show parent
                t.parents().prev("dt").click();
            }
        });
    } else {
        // click first
        t.find(".trackslist li:first").click();
    }
}
function spreadWordPage() {
    // populate flickrBlogBling with flickr images
    doFlickr("flickrBlogBling", 9, "blogbling", true);
    $("#blogBling").colorbox({ width: "800px", inline: true, opacity: 0.5, href: "#inline_blogbling" });

    // check which to show by search parameter or hash
    $(".rightsub #nav li").click(function() {
        // get id from tab id, find visible in trackitem, hide and show new one
        $(".spreadTheWord:visible").hide();
        $(".rightsub #nav li.active").removeClass("active");
        $("#" + $(this).attr("tabid")).show();
        $(this).addClass("active");

    });

    var page = location.hash;
    if (page != "") {
        // find id and show
        $.each($(".rightsub #nav li"), function() {
            if ("#" + $(this).attr("tabid") == page) {
                $(this).click();
            }
        });
    } else {
        // activate first by default
        $(".rightsub #nav li:first").click();

    }
    var bossRecName = $("#boss_recipient_name");
    var bossSenName = $("#boss_sender_name");
    var friendRecName = $("#friend_recipient_name");
    var friendSenName = $("#friend_sender_name");


    bossRecName.blur(function() { $(".boss_recipient_name").text(bossRecName.val()); });
    bossSenName.blur(function() { $(".boss_sender_name").text(bossSenName.val()); });
    friendRecName.blur(function() { $(".friend_recipient_name").text(friendRecName.val()); });
    friendSenName.blur(function() { $(".friend_sender_name").text(friendSenName.val()); });
    $(".round input").keydown(function(event) {
        // submit form
        if (event.keyCode == 13) {
            if (this.id.indexOf("boss") > -1) $("#boss_send").click();
            if (this.id.indexOf("friend") > -1) $("#friend_send").click();
        }
    });
    //add on focus remove content
    $(".round input").blur(function() {
        // get eq class and update
        var elem = $(this);
        $("." + this.id).text(elem.val());
        if (elem.val() == "") elem.val(elem.attr("defvalue"));

    })
    $(".round input").focus(function() {
        // remove default
        var elem = $(this);

        if (elem.val() == elem.attr("defvalue")) elem.val("");


    })


    // on focus of fields, erase default text
    // on click of button, call js on australia
    // also fire first wt tag
    $(".sendbut").click(function() {
        // grab prefix, grab sender name and email, recipient name and email, create a string and call function
        // hide messages

        var prefix = $(this).attr("groupid");
        $("#" + prefix + "Message").text("").hide();

        if (validate_email($("#" + prefix + "_sender_email").val()) && validate_email($("#" + prefix + "_recipient_email").val())) {
            var str = ("?s0={0}&s1={1}&r0={2}&r1={3}&prefix={4}").replace(
				"{0}", $("#" + prefix + "_sender_name").val()).replace(
				"{1}", $("#" + prefix + "_sender_email").val()).replace(
				"{2}", $("#" + prefix + "_recipient_name").val()).replace(
				"{3}", $("#" + prefix + "_recipient_email").val()).replace(
				"{4}", prefix);
            $(this).addClass("active");
            sendmail(str);
            // call webtreneds
            FireTrack("spread word " + prefix, "spread_word", "Link: Send Email to " + prefix);
        } else {
            alert('Invalid email format!');
        }

    });

}
function sendmail(str) {
    if (document.getElementById("auCampSendMail") == null) {
        $("<script id='auCampSendMail'> <\/script>").attr("src", "http://www.microsoft.com/australia/australia.campaigns/teched/mail.aspx" + encodeURI(str)).appendTo("head");

    } else {
        $("#auCampSendMail").attr("src", "");
        $("#auCampSendMail").attr("src", "http://wwwstaging/australia/australia.campaigns/teched/mail.aspx" + encodeURI(str));

    }
}

function request_receive(o) {
    //remove  script

    $(".sendbut").removeClass("active");

    $("#auCampSendMail").attr("src", "");
    $("#auCampSendMail").remove();
    // todo insert success message

    if (o.success) {
        // show .messageBox
        $("#" + o.prefix + "Message").text("Email Sent Successfully!").show();
        // call webtrends for success
        FireTrack("spread word success" + o.prefix, "spread_word", "Link: Send Email to " + o.prefix);
    } else {
        $("#" + o.prefix + "Message").text("Error Occurred! " + o.message).show();

    }
}


function validate_email(str) {
    // check fields before you send
    if (str === "") return false;

    var re = /^[\w\-]+(?:\.[\w\-]+)*@(?:[\w\-]+\.)+[a-zA-Z]{2,7}$/i;
    if (!re.test(str)) {
        return false;
    }
    return true;
}


function doFlickr(id, per_page, tag, useimgurl) {

    if (!per_page) per_page = 8;
    if (!tag) tag = "auteched";
    // api call to get photoset photos
    //var url = "http://api.flickr.com/services/feeds/photoset.gne?set=72157624138123360&nsid=38325340@N07&lang=en-us&format=json&jsoncallback=?";
    // for now use auteched tag
    //var url = "http://api.flickr.com/services/feeds/photos_public.gne?id=38325340@N07&tags=auteched&format=json&jsoncallback=?";
    // get more than 20 results, this is the best one by far
    var url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=707f43cd012e5ce7ea3fd2aeeafaadb3&format=json&jsoncallback=?"
		+ "&per_page=" + per_page
		+ "&user_id=38325340@N07"
		+ "&tags=" + tag
		+ "&extras=url_sq,url_o,path_alias";

    //url_o,url_sq,

    var flickr = $('<ul id="flickr">').appendTo("#" + id);

    $.getJSON(url, function(data) {

        $.each(data.photos.photo, function(i, item) {

            flickr.append(('<li><a href="{0}" title="{1} - right click and save target as..."><img src="{2}" alt="{3}"  /></a></li>')
            .replace("{0}", (!useimgurl) ? "http://www.flickr.com/photos/" + item.pathalias + "/" + item.id : item.url_o)
            .replace("{1}", item.title)
            .replace("{2}", item.url_sq)
            .replace("{3}", item.title));
        });
    });
}
function TechedTweet() {
    this.HtmlStr = '<li><div><img src="{0}" alt="{1}" /><span><a href="http://twitter.com/{2}">{3}</a>:{4}</span><span class="date">{5}</span></div></li>';
    this.Url = "http://search.twitter.com/search.json?callback=?";
    this.Id = '';
    this.SinceId = 0;
    this.HtmlObject = null;
    this.Success = false;
    this.Items = new Array();

    this.Init = function(id) {
        this.HtmlObject = $('<ul id="' + id + '">').appendTo("#tweetContainer");
        this.Id = id;

        this.GetItem(true, this);
    };
    this.BuildLi = function() {
        // put the first five in the array
        // shift and push or preseve index
        var toindex = Math.min(this.Items.length, 5);
        for (var x = 0; x < toindex; x++) {

            this.AddLi(this.Items[x]);
        }
        this.StopIndex = toindex - 1;
    };
    this.AddLi = function(o) {
        // add one htmlstr
        // prepare time
        var time = new Date(o.created_at);

        $(this.HtmlStr
            .replace("{0}", o.profile_image_url)
            .replace("{1}", o.from_user)
            .replace("{2}", o.from_user)
            .replace("{3}", o.from_user)
            .replace("{4}", o.text)
			.replace("{5}", time.toLocaleTimeString())
           ).prependTo(this.HtmlObject).slideDown("fast", function() {
               $(this).find("div").fadeIn("slow");
           });
        // animte here

    };
    this.RemoveLi = function(i) {
        // remove associated li
        this.HtmlObject.find("li").eq(i).remove();
        // animate removal
    };
    this.AddItem = function(o) {
        // add to items

        this.Items[this.Items.length] = o;
        // if length is more than 20; i should remove older ones
        if (this.Items.length > 20) this.RemoveItem(0);
    };
    this.RemoveItem = function(i) {
        // remove from items
        delete this.Items[i];
    };

    this.Interval = null;
    this.Start = function(CurrentScope) {
        // loop json get
        // stop rotation
        CurrentScope.StopRotating();
        CurrentScope.GetItem(false, CurrentScope);

    };
    this.Stop = function() {
        window.clearTimeout(this.Interval);
    };
    this.RotateInterval = null;
    this.StopIndex = 0;

    this.Rotate = function() {


        if (this.Items.length > 0)
            var CurrentScope = this;
        this.RotateInterval = window.setInterval(function() {
            CurrentScope.StopIndex++;

            if (CurrentScope.Items.length < CurrentScope.StopIndex + 1) CurrentScope.StopIndex = 0;
            // remove the fifth element or the last one
            var r = (Math.min(CurrentScope.HtmlObject.find("li").length, 5)) - 1;
            CurrentScope.RemoveLi(r);
            CurrentScope.AddLi(CurrentScope.Items[CurrentScope.StopIndex]);

        }, 9000);
    };
    this.StopRotating = function() {
        window.clearInterval(this.RotateInterval);
    };
    this.GetItem = function(firstTime, CurrentScope) {



        $.getJSON(CurrentScope.Url,
			{ "q": "#auteched OR @auteched",
			    "result_type": "recent",
			    "rpp": "20",
			    "lang": "en",
			    "since_id": CurrentScope.SinceId
			},
			function(data) {
			    // if no data returned for some reason, resume rotation


			    if (data) {

			        // results, also grab: refresh_url
			        CurrentScope.SinceId = data.max_id;
			        if (data.results.length > 0) {
			            $.each(data.results, function(i, item) {

			                CurrentScope.AddItem(data.results[data.results.length - i - 1]);
			            });
			            if (firstTime) CurrentScope.BuildLi();
			        }
			        //CurrentScope.Interval = window.setTimeout(eval("CurrentScope.GetItem(false,CurrentScope)"), 60000);
			        CurrentScope.Interval = window.setTimeout(function() { CurrentScope.Start(CurrentScope); }, 60000);
			        // if length of items is less than five, dont rotate
			        if (CurrentScope.Items.length > 5)
			            CurrentScope.Rotate();
			    }
			});

    }

}

function rssConnect() {

    var url = "http://pipes.yahoo.com/pipes/pipe.run?_id=7cb9c2d24c92dd2642d2edf9acffc4fa&_render=json&_callback=?";
    var tweets = $('<ul id="rssConnect">').appendTo("#rsscontainer");
    var display_count = 0;
    var maxItemsDisplayed = 3;
    var maxDescriptionLength = 200;

    $.getJSON(url, function(data) {
        $.each(data.value.items, function(i, item) {

            var description = removeHTMLTags(item.description).substring(0, maxDescriptionLength);
            var outPubDate = convertDate(item.pubDate);

            tweets.append('<li><a href="' + item.link + '">' + item.title + '</a> ' + description + '...<span class="sptime">' + outPubDate + '</span></li>');
            display_count += 1;
            if (display_count == maxItemsDisplayed) {
                return false;
            }

        });
    });
}


function convertDate(inString) {
    var inPubDate = inString;
    var date = inPubDate.substring(0, 16);
    var time = inPubDate.substring(17, 22);
    var outPubDate = date + ' at ' + time;
    return outPubDate;
}

function removeHTMLTags(inString) {
    /*Created by: Robert Nyman | http://robertnyman.com/ */
    var strInputCode = inString;
    /* 
    This line is optional, it replaces escaped brackets with real ones, 
    i.e. < is replaced with < and > is replaced with >
    */
    strInputCode = strInputCode.replace(/&(lt|gt);/g, function(strMatch, p1) {
        return (p1 == "lt") ? "<" : ">";
    });
    var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    return strTagStrippedText;
}


