/// <reference path="D:\Projects\DestinationOakland\trunk\Application\DestinationOakland\Scripts\jquery-1.3.2-vsdoc2.js" />
var newsRows;
var eventRows;
var socialRows;
var mainPics;
var mainPicsLinks;
var currentEventPage = 0;
var currentNewsPage = 0;
var currentSocialPage = 1;

//Browser Detection
var browser = navigator.appName;
var browserVersion = navigator.appVersion;

function destinationOaklandReady() {

    FixIE6();

    //Configure buttons to move when mouse is over them
    $("img[rel='slidebutton']").mouseover(function() {
        $(this).animate({ top: "166" }, 300);
    });

    $("img[rel='slidebutton']").mouseout(function() {
        $(this).animate({ top: "176" }, 300);
    });

    //Pull in the news, events and social items from SharePoint
    getNews();
    getEvents();
    getSocial();
    animateImages();
}

function FixIE6() {
    //Custom attribute noie6='true' added to an image will cause the image to not be displayed in IE 6
    //Custom attribute transparent='true' added to an image will cause the png image to be replaced with a gif
    //Custom attribute transparent='true' added to a table cell will cause the background image png to be replaced with a gif
    if (browser == "Microsoft Internet Explorer" && browserVersion.indexOf("MSIE 6") > 0) {
        $("img[noie6='true']").css("display", "none");
        $("img[transparent='true']").each(function() {
            var url = $(this).attr("src");
            var newurl = url.replace(".png", ".gif");
            $(this).attr("src", newurl);
        });
        $("td[transparent='true']").each(function() {
            var url = $(this).css("background-image");
            var newurl = url.replace(".png",".gif");
            $(this).css("background-image", newurl);
        });
        $("div[transparent='true']").each(function() {
            var url = $(this).css("background-image");
            var newurl = url.replace(".png", ".gif");
            $(this).css("background-image", newurl);
        });
    }
}

//Get list of events from SharePoint
function getEvents() {
    var soapEnv =
            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                <soapenv:Body> \
                     <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                        <listName>Events</listName> \
                        <query> \
                            <Query> \
                                <Where><Geq><FieldRef Name='EventDate' /><Value Type='DateTime'><Today /></Value></Geq></Where> \
                                <OrderBy> \
                                    <FieldRef Name='EventDate' Ascending='true' /> \
                                </OrderBy> \
                            </Query> \
                        </query> \
                        <viewFields> \
                            <ViewFields> \
                               <FieldRef Name='Title' /> \
                           </ViewFields> \
                        </viewFields> \
                    </GetListItems> \
                </soapenv:Body> \
            </soapenv:Envelope>";

    $.ajax({
        url: "/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processEventsResults,
        contentType: "text/xml; charset=\"utf-8\""
    });

}

//Get social feeds from proxy
function getSocial() {
    jQuery(function() {
        $("#pnlSocial").tweet({
            username: "destinationoak",
            join_text: "",
            avatar_size: 0,
            count: 1,
            page: currentSocialPage,
            loading_text: "loading tweet..."
        });
    });
}

function nextSocial() {
    currentSocialPage++;
    getSocial();
}

function prevSocial() {
    currentSocialPage--;
    if (currentSocialPage <= 1)
        currentSocialPage = 1;
    getSocial();
}

//Get news from SharePoint
function getNews() {
    var soapEnv =
            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                <soapenv:Body> \
                     <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                        <listName>News</listName> \
                        <query> \
                            <Query> \
                                <OrderBy> \
                                    <FieldRef Name='Last_x0020_Modified' Ascending='false' /> \
                                </OrderBy> \
                            </Query> \
                        </query> \
                        <viewFields> \
                            <ViewFields> \
                               <FieldRef Name='Title' /> \
                               <FieldRef Name='Body' /> \
                               <FieldRef Name='Summary' /> \
                           </ViewFields> \
                        </viewFields> \
                    </GetListItems> \
                </soapenv:Body> \
            </soapenv:Envelope>";

    $.ajax({
        url: "/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processNewsResults,
        contentType: "text/xml; charset=\"utf-8\""
    });

}

function processNewsResults(xData, status) {
    if (browser == "Microsoft Internet Explorer") {
        newsRows = xData.responseXML.getElementsByTagName("z:row");
    }
    else {
        newsRows = xData.responseXML.getElementsByTagNameNS('*', 'row');
    }
    showNewsPage(0);
}

function prevNews() {
    currentNewsPage--;
    if (currentNewsPage < 0)
        currentNewsPage = 0;
    showNewsPage(currentNewsPage);
}

function nextNews() {
    currentNewsPage++;
    if (currentNewsPage > newsRows.length - 1)
        currentNewsPage = newsRows.length - 1;
    showNewsPage(currentNewsPage);
}

function showNewsPage(pageid) {
    if (newsRows.length > pageid) {
        $('#newsReadMore').remove();
        var newsItem = $(newsRows).get(pageid)
        var NewsReadURL = "/Lists/News/DispForm.aspx?source=/&ID=";
        var summary = $($(newsItem).attr("ows_Summary")).html();
        var body = $($(newsItem).attr("ows_Body")).children().html();
        //        var article = "<a href='" + NewsReadURL + $(newsItem).attr("ows_ID") + "'>" + $(newsItem).attr("ows_Title") + "</a><hr/>" + body;
        // replaced "body" with "summary" > KRO 2011-02-10
        var article = "<a href='" + NewsReadURL + $(newsItem).attr("ows_ID") + "'>" + $(newsItem).attr("ows_Title") + "</a><hr/>" + summary;
        $('#pnlNews').html(article);
        //add ... for overflow
        sh = $('#pnlNews').attr('scrollHeight');
        var topdot;
        if (sh > 122) {
            if (browser == "Microsoft Internet Explorer")
                topdot = "112";
            else
                topdot = "109";
            $dots = $("<div style='position:absolute;top:" + topdot + "px;left:210px;z-index:10;color:#FFFFFF;background-color:#000000'>...</div>");
            $('#pnlNews').append($dots);
            //$readMore = $("<div id='newsReadMore' style='position:absolute;top:200px;left:200px;z-index:10;'><a style='color:#FFFFFF;background-color:#000000;font-size:10px;text-decoration:none;' href='" + NewsReadURL + $(newsItem).attr("ows_ID") + "'>Read More</a></div>");
            //$('#pnlNews').parent().parent().append($readMore);
        }
    }
}

function processEventsResults(xData, status) {
    if (browser == "Microsoft Internet Explorer") {
        eventRows = xData.responseXML.getElementsByTagName("z:row");
    }
    else {
        eventRows = xData.responseXML.getElementsByTagNameNS('*', 'row');
    }
    showEventsPage(0);
}

function prevEvents() {
    currentEventPage = currentEventPage - 3;
    if (currentEventPage < 0)
        currentEventPage = 0;
    showEventsPage(currentEventPage);
}

function nextEvents() {
    if (eventRows.length > currentEventPage + 3)
        currentEventPage = currentEventPage + 3;
    showEventsPage(currentEventPage);
}

function showEventsPage(indexid) {
    var article = "";
    var EventReadURL = "/Lists/Events/DispForm.aspx?source=/&ID=";

    for (var x = 0; x < 3; x++) {
        if (indexid + x < eventRows.length) {
            var eventItem = $(eventRows).get(indexid + x);
            if (eventItem != undefined)
                article += "<a href='" + EventReadURL + $(eventItem).attr("ows_ID") + "'>" + $(eventItem).attr("ows_Title") + "</a><br/>" + ParseDateTimeString($(eventItem).attr("ows_EventDate"));
            if (x < 3)
                article += "<br/><br/>";
        }
    }

    $('#pnlEvents').html(article);
}

function ParseDateTimeString(datestring) {
    var dt = datestring.split(' ');
    var d = dt[0].split('-');
    var t = dt[1].split(':');

    var newDate = new Date(d[0], d[1] - 1, d[2], t[0], t[1], t[2]);

    //Use date format library date.format.js
    var output = dateFormat(newDate, "mediumDate") + ", " + dateFormat(newDate, "longTime");
    return output;
}

function openSite(location) {
    var internalUrl = false;
    var url = "http://destinationoakland.com";
    switch (location) {
        case "facebook":
            url = "/media/socialnetworks/Pages/default.aspx";
            internalUrl = true;
            break;
        case "twitter":
            url = "http://twitter.com/destinationoak";
            break;
        case "myspace":
            url = "http://www.myspace.com";
            break;
        case "youtube":
            url = "http://www.youtube.com/destinationoakland";
            break;
        case "flickr":
            url = "http://www.flickr.com/photos/destinationoak/";
            break;
        case "newsrss":
            url = "/pages/rss.aspx";
            internalUrl = true;
            break;
    }
    if (internalUrl)
        window.location.href = url;
    else
        window.open(url, "externalSite");
}

function animateImages() {
    //Get list of images from SharePoint document library
    var soapEnv =
            "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                <soapenv:Body> \
                     <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                        <listName>Home Page Images</listName> \
                        <query> \
                            <Query> \
                                <OrderBy> \
                                    <FieldRef Name='Display_x0020_Order' Ascending='true' /> \
                                </OrderBy> \
                            </Query> \
                        </query> \
                        <viewFields> \
                            <ViewFields> \
                               <FieldRef Name='Title' /> \
                               <FieldRef Name='FileRef' /> \
                           </ViewFields> \
                        </viewFields> \
                    </GetListItems> \
                </soapenv:Body> \
            </soapenv:Envelope>";

    $.ajax({
        url: "/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: animateImages2,
        contentType: "text/xml; charset=\"utf-8\""
    });
}

function animateImages2(xData, status) {
    if (xData.responseXML.getElementsByTagName("z:row").length == 0) {
        homeImagesRows = xData.responseXML.getElementsByTagNameNS('*', 'row');
    }
    else {
        homeImagesRows = xData.responseXML.getElementsByTagName("z:row");
    }

    mainPics = [];
    mainPicsLinks = [];
    for (var cnt = 0; cnt < homeImagesRows.length; cnt++) {
        var imageItem = $(homeImagesRows).get(cnt)
        var url = $(imageItem).attr("ows_FileRef");
        var title = $(imageItem).attr("ows_Title");
        var desc = $(imageItem).attr("ows_Body");
        var link = $(imageItem).attr("ows_Article_x0020_URL");
        url = "/" + url.substring(url.indexOf(';#') + 2);

        mainPics[cnt] = {};
        mainPics[cnt].src = url;
        mainPics[cnt].alt = title;
        mainPics[cnt].body = desc;
        mainPicsLinks[cnt] = link;
    }
    updateOverlayText(0);
    $('#mainimage').crossSlide({
        sleep: 10,
        fade: 1
    }, mainPics, function callback(idx, img, idxOut, imgOut) {
        if (idxOut != undefined) {
            updateOverlayText(idx);
        }
    });
}

function updateOverlayText(idx) {
    $('#lblImageOverlay').fadeOut('normal', function () {
        $('#lblImageOverlayTitle').html(mainPics[idx].alt);
        $('#lblImageOverlayBody').html(mainPics[idx].body);
        $('#lblImageOverlay').fadeIn('normal');
    });

    var dotid = idx + 1;
    $('#picdot1').attr("src", "/_layouts/images/DestinationOakland/dot1off.jpg");
    $('#picdot2').attr("src", "/_layouts/images/DestinationOakland/dot2off.jpg");
    $('#picdot3').attr("src", "/_layouts/images/DestinationOakland/dot3off.jpg");
    $('#picdot4').attr("src", "/_layouts/images/DestinationOakland/dot4off.jpg");
    $('#picdot' + dotid).attr("src", "/_layouts/images/DestinationOakland/dot" + dotid + "on.jpg");

    //set go button URL
    $('#lnkGo').attr("href", mainPicsLinks[idx]);
}

function showSpecificImage(id) {
    $('#mainimage').crossSlideFreeze();
    $('#mainimage').html("<img src='" + mainPics[id].src + "' alt='" + mainPics[id].alt + "' border='0' />");
    updateOverlayText(id);
}

//GOV DELIVERY
function govDeliveryQuickSubscribe() {
    var email = document.getElementById("subscribeEmail").value;
    window.open("https://service.govdelivery.com/service/action/authenticate?function=login&code=MIOAKL&partner_id=5376&caller=multi_subscribe.html&custom_id=1161&login=" + email + "&origin=" + window.location.href);
}

//SUB PAGE SCRIPTS BELOW
function destinationOaklandReadySub() {
    var theHandle = document.getElementById("MSOTlPn_ToolPaneCaption");
    var theRoot = document.getElementById("MSOTlPn_Tbl");
    if (theHandle != null && theRoot != null) {
        Drag.init(theHandle, theRoot);
    }
    CheckBrowserVersion();

    var currentLoc = location.href.toLowerCase();
    //hide export event on events page
    if (currentLoc.indexOf('/lists/events/') > 0)
        $("a:contains('Export Event')").hide();    
    //hide print button on search page
    if (currentLoc.indexOf('searchcenter') > 0)
        $('#btnPrint').hide();
    //hide print button on interactive map page
    if (currentLoc.indexOf('interactivemap.aspx') > 0)
        $('#btnPrint').hide();
    //hide workspace creation checkbox on event pages
    $("span[title='Workspace']").parent().parent().parent().parent().hide();
    //hide workspace display on item display page
    $("a[name='SPBookmark_WorkspaceLink']").parent().parent().parent().hide();
    $("a[name='SPBookmark_Filter_x0020_Path']").parent().parent().parent().hide();
    $("a[name='SPBookmark_Expires']").parent().parent().parent().hide();
    //hide the created and modified by section on item detials pages
    $("td.ms-descriptiontext span:contains('Created at')").hide();
    $("td.ms-descriptiontext span:contains('Last modified at')").hide();
    //disable user profile links
    $("a[href*='userdisp']").each(function() {
        var txt = $(this).html();
        $(this).replaceWith(txt);
    });

    FixIE6();

    //Configure buttons to move when mouse is over them
    $("img[rel='slidebuttonsubpage']").mouseover(function() {
        $(this).animate({ top: "-230" }, 300);
    });

    $("img[rel='slidebuttonsubpage']").mouseout(function() {
        $(this).animate({ top: "-220" }, 300);
    });
}

function CheckBrowserVersion() {
    if (browser != "Microsoft Internet Explorer") {
        //Only IE browsers can edit content on the site
        jQuery('#siteActionMenuDiv').hide();
    }
}

function printPage() {
        var html = "<h1>Destination Oakland</h1>" + location.href + "<br/><br/><table width='100%' border='0'>";
               
        //Get publishing content area
        var sectiontitle = $("div.destoak-publishContentArea").html();
        var section = $("div[id*='PlaceHolderMain_DestOakPublishContentArea1_PageContent__ControlWrapper']").clone();
        $(section).find("a").each(function() { $(this).append(" (" + $(this).attr("href") + ")"); });
        var sectionhtml = $(section).html();
        if (sectionhtml!=null)
            html += "<tr><td><b>" + sectiontitle + "</b><br/>" + sectionhtml +"</td></tr><tr><td>&nbsp;</td></tr>";

        //Get article sections
        var tblarticles = $(".tbldestoakarticle").each(function() {
            var articleTitle = $(this).find("div.destoak-articleTitle").html();
            var articleBody = $(this).find("td.destoak-articleBody").clone();
            $(articleBody).find("a").each(function() { $(this).append(" (" + $(this).attr("href") + ")"); });
            html += "<tr><td><b>" + articleTitle + "</b><br/>" + $(articleBody).html() + "</td></tr><tr><td>&nbsp;</td></tr>";
        });

        //Get other web parts to print
        var tblarticles = $(".destoak-webpartTable").each(function() {
            var articleTitle = $(this).find("div.destoak-webpartTitleArea").html();
            var articleBody = $(this).find("div.destoak-webpartBodyArea").clone();
            if ($(this).find("div[id*='_CalendarView']").size() == 0 && $(this).find("td:contains('View:')").size() == 0)
                $(articleBody).find("a").each(function() { $(this).append(" (" + $(this).attr("href") + ")"); });
            else {
                html = "<link rel='stylesheet' type='text/css' href='/_layouts/1033/styles/calendar.css'/>" + html;
            }
            $(articleBody).find("script").each(function() { $(this).remove(); });
            html += "<tr><td><b>" + articleTitle + "</b><br/>" + $(articleBody).html() + "</td></tr><tr><td>&nbsp;</td></tr>";
        });

        var listData = $("#pageprintsection").find("#onetIDListForm").clone();
        listData.find("input").remove();
        if (listData.length > 0) {
            html += listData.html();
        }
        html += "</table>";
        //remove javascript "on" methods (ex. onClick, onMouseover)
        html = html.replace(/ on[a-zA-Z]*=".*?"/gi, "");
        html = html.replace(/ on[a-zA-Z]*='.*?'/gi, "");
        html = html.replace(/ on[a-zA-Z]*=.*? /gi, "");
        
        //open new window
        var printWP = window.open("", "printWebPart");
        printWP.document.open();
        //insert content
        printWP.document.write(html);
        printWP.document.close();
        //open print dialog
        printWP.print();
}

function ContactUs() {
    var tm = "http://www.oakgov.com/egov0003/index.jsp?sourcelink=" + document.location;
    DisplayGreeting = window.open(tm, "helpWin", "toolbar=no, status=no, width=587,height=600, scrollbars=yes");
}

