/**************************/
//Main stuff

$(document).ready(function() {
    jQuery.each($(".long-text"), function() {
        if ($(this).children("p").length > 1) {
            $(this).children("p:lt(1)").after("<p class='action'><a href='javascript:void(0);' class='read-more'>read more...</a></p>");
            $(this).children("p:last").after("<p class='action'><a href='javascript:void(0);' class='read-less'>read less...</a></p>");
            $(this).children("p:gt(1)").hide();

            $(".read-more").click(function() {
                $(this).parent().hide();
                $(this).parent().parent().children("p:gt(1)").show();
            });

            $(".read-less").click(function() {
                $(this).parent().parent().children("p").next().show();
                $(this).parent().parent().children("p:gt(1)").hide();
            });
        }
        else if ($(this).children("p").length == 1 && $(this).children("p").text().length > 300) {
            var fullHTML = $(this).children("p").html();
            var shortText = $(this).children("p").text().substring(0, 297) + "...";

            $(this).children("p").text(shortText);
            $(this).children("p").after("<p class='action'><a href='javascript:void(0);' class='read-more'>read more...</a></p>");
            $(this).children("p:last").after("<p>" + fullHTML + "</p>");
            $(this).children("p:last").after("<p class='action'><a href='javascript:void(0);' class='read-less'>read less...</a></p>").hide();
            $(this).children("p:last").hide();

            $(".read-more").click(function() {
                $(this).parent().hide();
                $(this).parent().parent().children("p:gt(1)").show();
                $(this).parent().parent().children("p:lt(2)").hide();
            });

            $(".read-less").click(function() {
                $(this).parent().hide();
                $(this).parent().parent().children("p:gt(1)").hide();
                $(this).parent().parent().children("p:lt(2)").show();
            });
        }
    });

    //Toggles collapsable content. Used on Bulletin Board.  
    //hide all of the elements with class TogglePaneContent
    $(".TogglePaneHeader").addClass("TogglePaneHeaderClosed");
    $(".TogglePaneContent").hide();

    //toggle the components with class TogglePaneContent and adds TogglePaneHeaderClosed class to corresponding head
    $(".TogglePaneHeader").click(function() {
        $(this).toggleClass("TogglePaneHeaderClosed")
        $(this).next(".TogglePaneContent").slideToggle(400);

    });

    //More portable version of the above for use throughout the site
    //hide all of the elements with class hidden-content
    $(".hidden-content").hide();

    //toggle the components with class hidden-content and adds open-content-displayer class to corresponding head
    $(".content-displayer").click(function() {
        $(this).toggleClass("open-content-displayer")
        $(this).next(".hidden-content").slideToggle(400);

    });

    $.ajax({ url: document.location.protocol + "//www.greaterphilachamber.com/JSONService.asmx/GetWebFeatures",
        data: "{}",
        dataType: "jsonp",
        success: function(json) {
            $("#website-features").html(eval(json));
        }
    });

    $.ajax({ url: document.location.protocol + "//www.greaterphilachamber.com/JSONService.asmx/GetAdvertisements",
        data: "{}",
        dataType: "jsonp",
        success: function(json) {
            $("#paid-ads").html(eval(json));

            var adRotation = setInterval("adSwitch()", 5000);

            $("#paid-ads").mouseover(function() {
                clearInterval(adRotation);
            }).mouseout(function() {
                adRotation = setInterval("adSwitch()", 5000);
            });
        }
    });

    //hides div#message when its span.closer is clicked
    $(".closer").click(function() {
        $(this).parents("#message").fadeOut();
    });

    //hides panel-2 on page load
    $("#panel-2").hide();

    //calls function
    $("#tab-nav li a").click(function() {

        //Figure out current panel via CSS class
        var curPanel = $("#tab-nav li a.current").attr("rel");

        //Panel moving to
        var $newPanel = $(this);

        //Remove highlighting - Add to just-clicked tab
        $("#tab-nav li a").removeClass("current");
        $newPanel.addClass("current");

        // Figure out ID of new list
        var panelID = $newPanel.attr("rel");

        if (panelID != curPanel) {

            // Fade out current list
            $("#" + curPanel).hide(10, function() {

                // Fade in new list on callback
                $("#" + panelID).show();

            });
        }

        // Don't behave like a regular link
        return false;
    });

    if ($("#flickr-images").length > 0) {
        //Get Flickr JSON to aggregate Photos
        $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=10135540@N03&format=json&jsoncallback=?", function(data) {
            var target = "#flickr-images"; // Where is it going?
            for (i = 0; i <= 3; i = i + 1) { // Loop through the 4 most recent, [0-3]
                var pic = data.items[i];
                var liNumber = i + 1; // Add class to each LI (1-10)
                var sourceSquare = (pic.media.m).replace("_m.jpg", "_s.jpg"); // Only get square thumbnails  
                $(target).append("<li class='flickr-image no-" + liNumber + "'><a title='" + pic.title + "' href='" + pic.link + "'><img src='" + sourceSquare + "' /></a></li>");
            }
        });
    }

    if ($('#rfpCats').length > 0) {
        $('#rfpCats').listnav({
            includeAll: false,
            includeOther: false,
            flagDisabled: true,
            noMatchText: 'Nothing matched your filter, please choose another letter.',
            showCounts: false,
            //cookieName: 'my-main-list', 
            prefixes: ['the', 'a']
        });
    }

    $(".chat-link").click(function() {
        window.open("http://www.websitealive8.com/2349/rRouter.asp?groupid=2349&websiteid=0&departmentid=2756&dl=" + escape(document.location.href), null, 'width=400,height=400', null);
        return false;
    });

});

function adSwitch() {
  var $active = $("#paid-ads a.active");
  
  if ( $active.length == 0 )
    $active = $('#paid-ads a:last');
  
  var $next =  $active.next().length ? $active.next() : $('#paid-ads a:first');
  
  $active.addClass('last-active');
  
  $next.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 2000, function() {
      $active.removeClass('active last-active');
    });
}

function CheckForCookies() {
    document.cookie = "testCookie";
    var cookieEnabled = (document.cookie.indexOf("testCookie") != -1) ? true : false;

    if (!cookieEnabled) {
        //Hide Page Content
        $("#primary-wrap > :not(#ctl00_divMessage)").hide();

        //Inform User They Don't Have Cookies Enabled
        ShowError("You must enable cookies to view this page.<br/><a href=\"http://www.google.com/cookies.html\" target=\"_blank\">Learn how to enable cookies</a>.");
    }
}

function popUp(strURL, strType, strHeight, strWidth) {
    var strOptions = "";
    if (strType == "console")
        strOptions = "resizable,height=" + strHeight + ",width=" + strWidth;

    if (strType == "fixed")
        strOptions = "status,height=" + strHeight + ",width=" + strWidth;

    if (strType == "elastic")
        strOptions = "toolbar,menubar,scrollbars,resizable,location,height=" + strHeight + ",width=" + strWidth;

    window.open(strURL, 'newWin', strOptions);
}

function printWindow() {
    bV = parseInt(navigator.appVersion);
    if (bV >= 4)
        window.print();
}

function ShowError(msg) {
    ClearMessage();

    $("#ctl00_divMessage").append($("<div id=\"error-message\"><h3>Error!</h3><p>" + msg + "</p>"));
    window.scrollTo(0, 0);
}

function ShowAlert(msg) {
    ClearMessage();

    $("#ctl00_divMessage").append($("<div id=\"attention-message\"><h3>Attention!</h3><p>" + msg + "</p>"));
    window.scrollTo(0, 0);
}

function ShowSuccess(msg) {
    ClearMessage();

    $("#ctl00_divMessage").append($("<div id=\"success-message\"><h3>Success!</h3><p>" + msg + "</p>"));
    window.scrollTo(0, 0);
}

function ClearMessage() {
    if ($("#ctl00_divMessage > *").length > 0)
        $("#ctl00_divMessage").empty();
}

function GetRadWindow() {
    var oWindow = null;

    if (window.radWindow)
        oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
    else if (window.frameElement && window.frameElement.radWindow)
        oWindow = window.frameElement.radWindow; //IE (and Moz az well)

    return oWindow;
}

function CloseWindow() {
    var oWindow = GetRadWindow();

    if (oWindow)
        oWindow.Close();
    else
        window.close();

    return false;
}

function CloseRedirect(url) {
    var oWindow = GetRadWindow();

    if (oWindow) {
        oWindow.Close();
        oWindow.BrowserWindow.location = url;
    }
    else
        window.location = url;
}

function swap(divNum, expanding) {
    var divContracted = document.getElementById("c" + divNum);
    var divExpanded = document.getElementById("e" + divNum);

    if (expanding) {
        divContracted.style.display = 'none';
        divExpanded.style.display = 'inline';
    }
    else {
        divContracted.style.display = 'inline';
        divExpanded.style.display = 'none';
    }
}

function ChangeHeaderAsNeeded(array) {
    // Whenever a checkbox in the GridView is toggled, we need to
    // check the Header checkbox if ALL of the GridView checkboxes are
    // checked, and uncheck it otherwise
    if (array != null) {
        // check to see if all other checkboxes are checked
        for (var i = 1; i < array.length; i++) {
            var cb = document.getElementById(array[i]);
            if (!cb.checked) {
                // Whoops, there is an unchecked checkbox, make sure
                // that the header checkbox is unchecked
                ChangeCheckBoxState(array[0], false);
                return;
            }
        }
        // If we reach here, ALL GridView checkboxes are checked
        ChangeCheckBoxState(array[0], true);
    }
}

function ChangeCheckBoxState(id, checkState) {
    var cb = document.getElementById(id);
    if (cb != null)
        cb.checked = checkState;
}

function ChangeAllCheckBoxStates(array, checkState) {
    // Toggles through all of the checkboxes defined in the CheckBoxIDs array
    // and updates their value to the checkState input parameter
    if (array != null) {
        for (var i = 0; i < array.length; i++)
            ChangeCheckBoxState(array[i], checkState);
    }
}

function ConfirmAction(array, msg) {
    ClearMessages();
    var hasItems = false;

    try {
        if (array != null) {
            if (GetCheckCount(array) != 0) {
                return confirm(msg);
            }
            else {
                ShowError("Error, message: No items have been selected. Please select at least 1 item.");
                return false;
            }
        }
    }
    catch (e) {
        ShowError("Error, message: No items selected.");
        return false;
    }
}

function GetCheckCount(array) {
    var count = 0 - 0;

    for (var i = 0; i < array.length; i++) {
        var chk = document.getElementById(array[i]);
        if (chk.checked)
            count++;
    }

    return count;
}

function refreshGrid(clientID, uniqueID) {
    if (document.getElementById(clientID))
        window[clientID].AjaxRequest(uniqueID, 'Rebind');
}

function OnEditorLoad(editor) {
    var body = editor.GetContentArea();
    body.id = "primary";
    body.style.padding = "15px";
    body.style.textAlign = "left";
    body.style.overflow = "auto";
}  

//  AliveChat Live Site Monitor Code
function wsa_include_js() {
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', 'http://www.websitealive8.com/2349/Visitor/vTracker_v2.asp?websiteid=0&groupid=2349');
    document.getElementsByTagName('head').item(0).appendChild(js);
}
// End AliveChat Live Site Monitor Code

function getQueryStringParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}