
jQuery.ITN = {
    getLocalizedResources: //Helper function to get globalized resources via JS
    function(resourceKeys, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/services/localizedresourceservice.asmx/GetLocalizedResources",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ resourceKeys: resourceKeys }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getMessageTemplate: //Helper function to get a Message Template
    function(messageTemplateId, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/services/messagetemplateservice.asmx/GetMessageTemplate",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ messageTemplateId: messageTemplateId }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getCurrentMemberInfo: //Helper function to get information about the current member.
    function(success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/services/memberservice.asmx/GetCurrentMemberInfo",
            contentType: "application/json; charset=utf-8",
            data: "",
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getMemberInfo: //Helper function to get information about the specified member.
    function(userName, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/services/memberservice.asmx/GetMemberInfo",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ userName: userName }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getCommunityInfo: //Helper function to get information about the specified community.
    function(communityUrl, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/services/communityservice.asmx/GetCommunityInfo",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ communityUrl: communityUrl }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getTotalPendingCommunityCount: //Helper function to get the total number of pending communities (for the current web application)
    function(success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communityapprovalservice.asmx/TotalPendingCommunityCount",
            contentType: "application/json; charset=utf-8",
            data: "",
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getPendingCommunities: //Helper function to get a collection of pending communities (for the current web application)
    function(args, success, error) {
        args =
			jQuery.extend({
			    pageSize: 10,
			    pageNumber: 1,
			    sortBy: 0
			}, args);
			
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communityapprovalservice.asmx/GetPendingCommunities",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ pageNumber: args.pageNumber, pageSize: args.pageSize, sortBy: args.sortBy }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getPendingCommunityInfo: //Helper function to get details about a specific pending community
    function(communityUrl, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communityapprovalservice.asmx/GetPendingCommunity",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ communityUrl: communityUrl }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },
    
    approvePendingCommunity: //Helper function to approve the specified community.
    function(communityUrl, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communityapprovalservice.asmx/ApproveCommunity",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ communityUrl: communityUrl }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },
    
    rejectPendingCommunity: //Helper function to reject the specified community (with the specified rejection notification)
    function(communityUrl, rejectEmailSubject, reasonForDecline, success, error) {
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communityapprovalservice.asmx/RejectCommunity",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ communityUrl: communityUrl, rejectEmailSubject: rejectEmailSubject, reasonForDecline: reasonForDecline }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },
    
    getTotalCommunityCount: //Helper function to get the total number of communities for the specified search term.
    function(searchTerm, success, error) {

        //Get the total number of pages
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communitysearchservice.asmx/TotalCommunityCount",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ searchTerm: searchTerm }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        });
    },

    getCommunitySearchResults: //Helper function to get community search results.
    function(args, success, error) {
        args =
			jQuery.extend({
			    searchTerm: "",
			    pageSize: 10,
			    pageNumber: 1,
			    sortBy: 0
			}, args);

        //Get the search results.
        $.ajax({
            type: "POST",
            url: "/_layouts/itn/community/communitysearchservice.asmx/Search",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ searchTerm: args.searchTerm, pageNumber: args.pageNumber, pageSize: args.pageSize, sortBy: args.sortBy }),
            dataType: "json",
            timeout: 1000 * 60,
            success: success,
            error: error
        })
    }
};

/***********************************************************************
Helper Functions
************************************************************************/

function addInputFocusStyles(classDefault, classOnFocus) {
    $('input[type="text"]').addClass(classDefault);
    $('input[type="text"]').focus(function() {
        $(this).removeClass(classDefault).addClass(classOnFocus);
    });
    $('input[type="text"]').blur(function() {
        $(this).removeClass(classOnFocus).addClass(classDefault);
    });

    $('textarea').addClass(classDefault);
    $('textarea').focus(function() {
        $(this).removeClass(classDefault).addClass(classOnFocus);
    });
    $('textarea').blur(function() {
        $(this).removeClass(classOnFocus).addClass(classDefault);
    });
}


function AllResults() {
    var url = "/Search/Pages/SearchResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}
function MyNotebookSearch() {
    var url = "/Search/Pages/MyNotebookResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}
function CommunitySearch() {
    var url = "/Search/Pages/CommunityResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}
function ResourcesSearch() {
    var url = "/Search/Pages/ResourcesResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}
function LibrarySearch() {
    var url = "/Search/Pages/LibraryResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}
function ClassroomResourcesSearch() {
    var url = "/Search/Pages/ClassroomResourcesResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}
function EventsSearch() {
    var url = "/Search/Pages/EventsResults.aspx?k=" + $.jqURL.get('k');
    window.location = url;
}

var piln_searchStats;
var piln_searchTotalResults;
piln_searchTotalResults = 0;

function ChangeSearchSortBy() {
    var url;
    if ($.jqURL.get('v1') == null) {
        var myArray = new Array();
        myArray["v1"] = "date";
        url = $.jqURL.set(myArray);
    }
    else {
        url = $.jqURL.strip({ keys: 'v1' });
    }

    window.location = url;
}

function ParseSearchStatsLocalized(lcid) {

    var regex;
    if (lcid == 1058)
        regex = /(?:Результат(?:и)? (\d+-\d+) (?:і)?з )(\d{1,3}(?:,\d\d\d)*)(?: \(приблизно\))?(?:\.)/;
    else
        regex = /(?:Result(?:s)? (\d+-\d+) of (?:about )?)(\d{1,3}(?:,\d\d\d)*)(?:\.)/;


    var text = $("div.srch-stats:eq(0)").text();
    if (text == "" || text == null) {
        piln_searchStats = "No Items Found";
        if (lcid == 1058) {
            piln_searchStats = "Не знайдено";
        }
        piln_searchTotalResults = 0;

        $("#piln_searchStatsText").append(piln_searchStats);
        $("#piln_searchSort").hide();
        $("#SRST").hide();
        return;
    }

    piln_searchStats = regex.exec(text)[0];
    piln_searchTotalResults = parseInt(regex.exec(text)[2].replace(",", ""));
    $("div.srch-stats").hide();
    $("#SRST").hide();

    //Populate search stats
    $("#piln_searchStatsText").append(piln_searchStats);

    //Display the current sort
    if ($.jqURL.get('v1') == "date") {
        $("#piln_searchSortSelect > option[value='']").attr("selected", null);
        $("#piln_searchSortSelect > option[value='date']").attr("selected", "selected");
    }
}

//TODO: rename this method to not be specific to Resources.
function RewriteITNResourceUrls(url, lcid) {
    url = RewriteUrl(url, "http://(.*)/Resources/Lists/Library/DispForm\.aspx\\?ID=(\d*)", "http://$1/Resources/Pages/ITNLibraryViewer.aspx?resid=$2");
    url = RewriteUrl(url, "http://(.*)/Resources/Lists/Resources/DispForm\.aspx\\?ID=(\d*)", "http://$1/Resources/Pages/ITNResourceViewer.aspx?resid=$2");

    //Handle Discussions (Discussions and Reply Urls are handle slightly different from each other)

    //Workspace Dicussions (Workspaces ALWAYS use "Discussions" as list name regardless of LCID).
    url = RewriteUrl(url, "http://(.*?)/Workspaces/(.*?)/Lists/Discussions/DispForm\.aspx\?ID=(\d+)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?rid=$3");  //replies
    url = RewriteUrl(url, "http://(.*?)/Workspaces/(.*?)/Lists/Discussions/(.*)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?DiscussionName=$3");  //discussions

    //Community Dicussions (Communities may use "Discussions", "Team Discussion", or "Обговорення у групі" for the list name)
    url = RewriteUrl(url, "http://(.*?)/Communities/(.*?)/Lists/Discussions/DispForm\.aspx\?ID=(\d+)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?rid=$3");  //replies
    url = RewriteUrl(url, "http://(.*?)/Communities/(.*?)/Lists/Discussions/(.*)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?DiscussionName=$3");  //discussions

    url = RewriteUrl(url, "http://(.*?)/Communities/(.*?)/Lists/Team(?:(?:%20)| )Discussion/DispForm\.aspx\?ID=(\d+)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?rid=$3");  //replies
    url = RewriteUrl(url, "http://(.*?)/Communities/(.*?)/Lists/Team(?:(?:%20)| )Discussion/(.*)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?DiscussionName=$3");  //discussions

    url = RewriteUrl(url, "http://(.*?)/Communities/(.*?)/Lists/Обговорення(?:(?:%20)| )у(?:(?:%20)| )групі/DispForm\.aspx\?ID=(\d+)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?rid=$3");  //replies
    url = RewriteUrl(url, "http://(.*?)/Communities/(.*?)/Lists/Обговорення(?:(?:%20)| )у(?:(?:%20)| )групі/(.*)", "http://$1/Communities/$2/Pages/DiscussionView.aspx?DiscussionName=$3");  //discussions

    return url;    
}



function RewriteUrl(url, regExpString, replacementString) {

    var regExp = new RegExp(regExpString, "g");

    if (regExp.test(url))
        url = url.replace(regExp, replacementString);
        
    return url;
}


function GetFancyContent(url, lcid) {
    var noteBookPublicRegex = new RegExp("http://.*/MyNotebook/Public Documents/.*");
    var noteBookPrivateRegex = new RegExp("http://.*/MyNotebook/Private Documents/.*");
    var communityRegex = new RegExp("http://.*/Community/.*");
    var communitiesRegex = new RegExp("http://.*/Communities/.*");
    var libraryRegex = new RegExp("http://.*/Resources/Lists/Library/.*");
    var classroomRegex = new RegExp("http://.*/Resources/Lists/Resources/.*");
    var partnerEventsRegex = new RegExp("http://.*/Resources/Lists/PartnerEvents/.*");
    var communityEventsRegex = new RegExp("http://.*/Resources/Lists/CommunityEvents/.*");


    var markup = "<a href='" + url + "'>" + url + "</a>";
    if (noteBookPublicRegex.test(url)) {
        markup = "<a href='/MyNoteBook/'>My Notebook</a>&nbsp;&gt;&nbsp;<a href='/MyNoteBook/Public%20Documents/'>Public Documents</a>";
        if (lcid == 1058) {
            markup = "<a href='/MyNoteBook/'>Мій блокнот</a>&nbsp;&gt;&nbsp;<a href='/MyNoteBook/Public%20Documents/'>відкриті документи</a>";
        }
    }
    else if (noteBookPrivateRegex.test(url)) {
        markup = "<a href='/MyNoteBook/'>My Notebook</a>&nbsp;&gt;&nbsp;<a href='/MyNoteBook/Private%20Documents/'>Private Documents</a>";
        if (lcid == 1058) {
            markup = "<a href='/MyNoteBook/'>Мій блокнот</a>&nbsp;&gt;&nbsp;<a href='/MyNoteBook/Private%20Documents/'>приватні документи</a>";
        }
    }
    else if (communityRegex.test(url)) {
        markup = "<a href='/Community/'>Communities</a>";
        if (lcid == 1058) {
            markup = "<a href='/Community/'>спільноти</a>";
        }
    }
    else if (communitiesRegex.test(url)) {
        markup = "<a href='" + url + "'>Communities</a>";
        if (lcid == 1058) {
            markup = "<a href='" + url + "'>спільноти</a>";
        }
    }
    else if (partnerEventsRegex.test(url)) {
        markup = "<a href='/Resources/'>Resources</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/PartnerEvents'>Partner Events</a>";
        if (lcid == 1058) {
            markup = "<a href='/Resources/'>Ресурси</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/PartnerEvents'>Партнер події</a>";
        }
    }
    else if (communityEventsRegex.test(url)) {
        markup = "<a href='/Resources/'>Resources</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/CommunityEvents'>Community Events</a>";
        if (lcid == 1058) {
            markup = "<a href='/Resources/'>Ресурси</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/CommunityEvents'>Події Спільноти</a>";
        }
    }
    else if (libraryRegex.test(url)) {
        markup = "<a href='/Resources/'>Resources</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/Library'>Library</a>";
        if (lcid == 1058) {
            markup = "<a href='/Resources/'>Ресурси</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/Library'>бібліотеку</a>";
        }
    }
    else if (classroomRegex.test(url)) {
        markup = "<a href='/Resources/'>Resources</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/Resources'>Classroom Resources</a>";
        if (lcid == 1058) {
            markup = "<a href='/Resources/'>Ресурси</a>&nbsp;&gt;&nbsp;<a href='/Resources/Lists/Resources'>Pесурс класної кімнати</a>";
        }
    }

    return markup;
}

function AppendPages(lcid) {
    if (typeof (piln_searchTotalResults) == "undefined")
        return;

    var totalPages = Math.ceil(piln_searchTotalResults / 10);

    var previous = "Previous";
    var next = "Next";

    if (lcid == 1058) {
        previous = "Попередній";
        next = "Далі";
    }
    
    var currentItem = 1;
    if ($.jqURL.get('start1') != null)
        currentItem = parseInt($.jqURL.get('start1'));

    var currentPage = Math.floor((currentItem + 9) / 10);
    var startPage = Math.max(1, Math.floor(currentPage / 5) * 5);

    if (currentPage != 1)
        $("#piln-gridViewTd").append("<a href='javascript:SelectPage(" + (currentPage - 1) + ");'>" + previous + "</a>");

    var maxPages = startPage + 5;
    if (maxPages > totalPages)
        maxPages = totalPages + 1;

    for (var i = startPage; i < maxPages; i++) {
        if (currentPage != i)
            $("#piln-gridViewTd").append("<a href='javascript:SelectPage(" + i + ");'>" + i + "</a>");
        else
            $("#piln-gridViewTd").append("<span>" + i + "</span>");
    }

    if (totalPages > maxPages)
        $("#piln-gridViewTd").append("<a href='javascript:SelectPage(" + (currentPage + 1) + ");'>" + next + "</a>");
}

function SelectPage(pageNumber) {
    var myArray = new Array();
    myArray["start1"] = pageNumber * 10 - 9;

    var url = $.jqURL.set(myArray);
    window.location = url;
}


/***********************************************************************
Custom Scripts for Branding
************************************************************************/

$(document).ready(function() {

    // Hide every image element that has a src the rectangle image
    $('img[src="/_layouts/images/rect.gif"]').hide();

    // New html to insert
    var imgHtml = '<img src="/_layouts/itn/images/20x20_btn_arrow_PILN.png" alt="New" />';

    // Iterate through each anchor element with class="ms-addnew" and append
    // imgHtml to anchor’s inner html.

    $('a[class="ms-addnew"]').each(function() {
        $(this).html($(this).html() + imgHtml);
    });

    //Remove the double nav bar that appears on the left side.
    $("td .ms-banner td img[src$='piln_globalNavDivider.jpg']:eq(0)").remove();
    $("td .ms-banner td img[src$='piln_globalNavDivider.jpg']:eq(0)").remove();
    
});







/***********************************************************************
Custom Plugins
************************************************************************/

// wrap the $ into a private function
(function($) {
    // initiate the jQuery Plugin
    $.fn.myPlugin = function() {
        // loop through each matched selector
        this.each(function() {
            // do stuff here
        });
        // return itself to maintain chainability
        return $(this);
    }
    // make the $ reference to the jQuery object
})(jQuery);

(function($) {
    $.fn.stripHtml = function() {
        var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
        this.each(function() {
            $(this).val(
                $(this).val().replace(regexp, "")
            );
        });
        return $(this);
    }
})(jQuery);

/*
various manipulations on url strings and windows.  
all functions can also take a window object as an argument,
for example {win:opener}
but will default to current window if none is passed.

public functions:

-------------------------
.url({ 
win:window object 
})
-------------------------
returns the whole url string
like win.location.href

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"
	
$.jqURL.url() returns "http://www.mysite.com?var1=1&var2=2&var3=3"
	
	
------------------------------
.loc(urlstr:string, 
{ 
win:window object, 
w:integer, 
h:integer, 
t:integer,
l:integer,
wintype:string('_top'[default],'_blank','_parent') )
})
------------------------------																			 
- directs passed in window to urlstr, which is required
- works like window.location.href = 'myurl'
- but you can also use it to pop open a new window by passing in "_blank" as the wintype
- if popping open a window, defaults to center of screen

so
$.jqURL.loc('http://www.google.com',
{w:200,h:200,wintype:'_blank'});
would open Google in a new centered 200x200 window
	
or, locate an url to any named window:
$.jqURL.loc('http://www.google.com',{ win:mywindow });
opens Google in mywindow


------------------------------
.qs({ 
ret:string('string'[default],'object'), 
win:window object })
------------------------------
returns querystring, either string (pass ret:'string' [default])
or object (pass ret:'object') 

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"

$.jqURL.qs();
returns "var1=1&var2=2&var3=3"
	
$.jqURL.qs({ ret:'object' });
returns Object var1=1,var2=2,var3=3


------------------------------
.strip({ keys:string(list of keys to strip), win:window object })
------------------------------
if passed with no arguments, returns url with '?' and query string removed
if you pass in list of keys, it returns url with the specified key-value pairs removed

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"

$.jqURL.strip();
will return
"http://www.mysite.com"
	
$.jqURL.strip({ keys:'var1,var2' });
will return
"http://www.mysite.com?var3=3"
	
	
-------------------------------------
.get(key, {win:window object})
-------------------------------------
returns value of passed in querystring key

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"
$.jqURL.get('var2');
will return 2

--------------------------------------
.set(hash, {win:window object})
--------------------------------------
returns the window's url, but with the keys/values set in the query string
if the keys already exist, re-sets the value
if they don't exist, they're appended onto the query string

*/

jQuery.jqURL = {

    url: // returns a string
	function(args) {
	    args =
			jQuery.extend({
			    win: window
			},
			args);
	    return args.win.location.href;
	},

    loc:
	function(urlstr, args) {
	    args =
			jQuery.extend({
			    win: window,
			    w: 500,
			    h: 500,
			    wintype: '_top'
			},
			args);

	    if (!args.t) {
	        args.t = screen.height / 2 - args.h / 2;
	    }
	    if (!args.l) {
	        args.l = screen.width / 2 - args.w / 2;
	    }
	    if (args['wintype'] == '_top') {
	        args.win.location.href = urlstr;
	    }
	    else {
	        open(
			urlstr,
			args['wintype'],
			'width=' + args.w + ',height=' + args.h + ',top=' + args.t + ',left=' + args.l + ',scrollbars,resizable'
			);

	    }
	    return;
	},

    qs:
	function(args) {
	    args = jQuery.extend({
	        ret: 'string',
	        win: window
	    },
		args);

	    if (args['ret'] == 'string') {
	        return jQuery.jqURL.url({ win: args.win }).split('?')[1];
	    }

	    else if (args['ret'] == 'object') {

	        var qsobj = {};
	        var thisqs = jQuery.jqURL.url({ win: args.win }).split('?')[1];

	        if (thisqs) {
	            var pairs = thisqs.split('&');
	            for (i = 0; i < pairs.length; i++) {
	                var pair = pairs[i].split('=');
	                qsobj[pair[0]] = pair[1];
	            }
	        }
	        return qsobj;
	    }
	},

    strip:
	function(args) {
	    args = jQuery.extend({
	        keys: '',
	        win: window
	    },
			args);

	    if (jQuery.jqURL.url().indexOf('?') == -1) { // no query string found
	        return jQuery.jqURL.url({ win: args.win });
	    }
	    // if no keys passed in, just return url with no querystring
	    else if (!args.keys) {
	        return jQuery.jqURL.url({ win: args.win }).split('?')[0];
	    }
	    else { //return stripped url

	        var qsobj = jQuery.jqURL.qs({ ret: 'object', win: args.win });  // object with key/value pairs		
	        var counter = 0;
	        var url = jQuery.jqURL.url({ win: args.win }).split('?')[0] + '?';
	        var amp = '';

	        for (var key in qsobj) {
	            if (args.keys.indexOf(key) == -1) {
	                // pass test, add this key/value to string
	                amp = (counter) ? '&' : '';
	                url = url + amp + key + '=' + qsobj[key];
	                counter++;
	            }
	        }
	        return url;
	    }
	},

    get:
	function(key, args) {
	    args = jQuery.extend({
	        win: window
	    }, args);

	    qsobj = jQuery.jqURL.qs({ ret: 'object', win: args.win });
	    return qsobj[key];
	},

    set:
	function(hash, args) {
	    args = jQuery.extend({
	        win: window
	    }, args);

	    // get current querystring
	    var qsobj = jQuery.jqURL.qs({ ret: 'object', win: args.win });

	    // add/set values from hash
	    for (var i in hash) {
	        qsobj[i] = hash[i];
	    }

	    var qstring = '';
	    var counter = 0;
	    var amp = '';

	    // turn qsobj into string
	    for (var k in qsobj) {
	        amp = (counter) ? '&' : '';
	        qstring = qstring + amp + k + '=' + qsobj[k];
	        counter++;
	    }
	    return jQuery.jqURL.strip({ win: args.win }) + '?' + qstring;
	}

};

/*
* jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
* htt        lman.com/projects/jquery-bbq-plugin/
* 
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($, p) { var i, m = Array.prototype.slice, r = decodeURIComponent, a = $.param, c, l, v, b = $.bbq = $.bbq || {}, q, u, j, e = $.event.special, d = "hashchange", A = "querystring", D = "fragment", y = "elemUrlAttr", g = "location", k = "href", t = "src", x = /^.*\?|#.*$/g, w = /^.*\#/, h, C = {}; function E(F) { return typeof F === "string" } function B(G) { var F = m.call(arguments, 1); return function() { return G.apply(this, F.concat(m.call(arguments))) } } function n(F) { return F.replace(/^[^#]*#?(.*)$/, "$1") } function o(F) { return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/, "$1") } function f(H, M, F, I, G) { var O, L, K, N, J; if (I !== i) { K = F.match(H ? /^([^#]*)\#?(.*)$/ : /^([^#?]*)\??([^#]*)(#?.*)/); J = K[3] || ""; if (G === 2 && E(I)) { L = I.replace(H ? w : x, "") } else { N = l(K[2]); I = E(I) ? l[H ? D : A](I) : I; L = G === 2 ? I : G === 1 ? $.extend({}, I, N) : $.extend({}, N, I); L = a(L); if (H) { L = L.replace(h, r) } } O = K[1] + (H ? "#" : L || !K[1] ? "?" : "") + L + J } else { O = M(F !== i ? F : p[g][k]) } return O } a[A] = B(f, 0, o); a[D] = c = B(f, 1, n); c.noEscape = function(G) { G = G || ""; var F = $.map(G.split(""), encodeURIComponent); h = new RegExp(F.join("|"), "g") }; c.noEscape(",/"); $.deparam = l = function(I, F) { var H = {}, G = { "true": !0, "false": !1, "null": null }; $.each(I.replace(/\+/g, " ").split("&"), function(L, Q) { var K = Q.split("="), P = r(K[0]), J, O = H, M = 0, R = P.split("]["), N = R.length - 1; if (/\[/.test(R[0]) && /\]$/.test(R[N])) { R[N] = R[N].replace(/\]$/, ""); R = R.shift().split("[").concat(R); N = R.length - 1 } else { N = 0 } if (K.length === 2) { J = r(K[1]); if (F) { J = J && !isNaN(J) ? +J : J === "undefined" ? i : G[J] !== i ? G[J] : J } if (N) { for (; M <= N; M++) { P = R[M] === "" ? O.length : R[M]; O = O[P] = M < N ? O[P] || (R[M + 1] && isNaN(R[M + 1]) ? {} : []) : J } } else { if ($.isArray(H[P])) { H[P].push(J) } else { if (H[P] !== i) { H[P] = [H[P], J] } else { H[P] = J } } } } else { if (P) { H[P] = F ? i : "" } } }); return H }; function z(H, F, G) { if (F === i || typeof F === "boolean") { G = F; F = a[H ? D : A]() } else { F = E(F) ? F.replace(H ? w : x, "") : F } return l(F, G) } l[A] = B(z, 0); l[D] = v = B(z, 1); $[y] || ($[y] = function(F) { return $.extend(C, F) })({ a: k, base: k, iframe: t, img: t, input: t, form: "action", link: k, script: t }); j = $[y]; function s(I, G, H, F) { if (!E(H) && typeof H !== "object") { F = H; H = G; G = i } return this.each(function() { var L = $(this), J = G || j()[(this.nodeName || "").toLowerCase()] || "", K = J && L.attr(J) || ""; L.attr(J, a[I](K, H, F)) }) } $.fn[A] = B(s, A); $.fn[D] = B(s, D); b.pushState = q = function(I, F) { if (E(I) && /^#/.test(I) && F === i) { F = 2 } var H = I !== i, G = c(p[g][k], H ? I : {}, H ? F : 2); p[g][k] = G + (/#/.test(G) ? "" : "#") }; b.getState = u = function(F, G) { return F === i || typeof F === "boolean" ? v(F) : v(G)[F] }; b.removeState = function(F) { var G = {}; if (F !== i) { G = u(); $.each($.isArray(F) ? F : arguments, function(I, H) { delete G[H] }) } q(G, 2) }; e[d] = $.extend(e[d], { add: function(F) { var H; function G(J) { var I = J[D] = c(); J.getState = function(K, L) { return K === i || typeof K === "boolean" ? l(I, K) : l(I, L)[K] }; H.apply(this, arguments) } if ($.isFunction(F)) { H = F; return G } else { H = F.handler; F.handler = G } } }) })(jQuery, this);
/*
* jQuery hashchange event - v1.2 - 2/11/2010
* http://benalman.com/projects/jquery-hashchange-plugin/
* 
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($, i, b) { var j, k = $.event.special, c = "location", d = "hashchange", l = "href", f = $.browser, g = document.documentMode, h = f.msie && (g === b || g < 8), e = "on" + d in i && !h; function a(m) { m = m || i[c][l]; return m.replace(/^[^#]*#?(.*)$/, "$1") } $[d + "Delay"] = 100; k[d] = $.extend(k[d], { setup: function() { if (e) { return false } $(j.start) }, teardown: function() { if (e) { return false } $(j.stop) } }); j = (function() { var m = {}, r, n, o, q; function p() { o = q = function(s) { return s }; if (h) { n = $('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow; q = function() { return a(n.document[c][l]) }; o = function(u, s) { if (u !== s) { var t = n.document; t.open().close(); t[c].hash = "#" + u } }; o(a()) } } m.start = function() { if (r) { return } var t = a(); o || p(); (function s() { var v = a(), u = q(t); if (v !== t) { o(t = v, u); $(i).trigger(d) } else { if (u !== t) { i[c][l] = i[c][l].replace(/#.*/, "") + "#" + u } } r = setTimeout(s, $[d + "Delay"]) })() }; m.stop = function() { if (!n) { r && clearTimeout(r); r = 0 } }; return m })() })(jQuery, this);

var _tmplCache = {};
jQuery.parseTemplate = function(str, data) {
    /// <summary>
    /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &amp;rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            //                        str
            //                  .replace(/[\r\t\n]/g, " ")
            //                  .split("<#").join("\t")
            //                  .replace(/((^|#>)[^\t]*)'/g, "$1\r")
            //                  .replace(/\t=(.*?)#>/g, "',$1,'")
            //                  .split("\t").join("');")
            //                  .split("#>").join("p.push('")
            //                  .split("\r").join("\\'") + "');}return p.join('');";

            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err + " # >";
};

/*
http://www.JSON.org/json2.js
2010-03-20

Public Domain.

NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

See http://www.JSON.org/js.html


This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.


This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value       any JavaScript value, usually an object or array.

replacer    an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space       an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear()   + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate())      + 'T' +
f(this.getUTCHours())     + ':' +
f(this.getUTCMinutes())   + ':' +
f(this.getUTCSeconds())   + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function() {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function(key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function(key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        // If the string contains no control characters, no quote characters, and no
        // backslash characters, then we can safely slap some quotes around it.
        // Otherwise we must also replace the offending characters with safe escape
        // sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function(a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or
                // null.

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.

                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function(value, replacer, space) {

            // The stringify method takes a value and an optional replacer, and an optional
            // space parameter, and returns a JSON text. The replacer can be a function
            // that can replace values, or an array of strings that will select the keys.
            // A default replacer method can be provided. Use of the space parameter can
            // produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that
            // many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.
            // Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function(text, reviver) {

            // The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

                // The walk method is used to recursively walk the resulting structure so
                // that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            // Parsing happens in four stages. In the first stage, we replace certain
            // Unicode characters with escape sequences. JavaScript handles many characters
            // incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function(a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            // In the second stage, we run the text against regular expressions that look
            // for non-JSON patterns. We are especially concerned with '()' and 'new'
            // because they can cause invocation, and '=' because it can cause mutation.
            // But just to be safe, we want to reject all unexpected forms.

            // We split the second stage into 4 regexp operations in order to work around
            // crippling inefficiencies in IE's and Safari's regexp engines. First we
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
            // replace all simple value tokens with ']' characters. Third, we delete all
            // open brackets that follow a colon or comma or that begin the text. Finally,
            // we look to see that the remaining characters are only whitespace or ']' or
            // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                // In the third stage we use the eval function to compile the text into a
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                // in JavaScript: it can begin a block or an object literal. We wrap the text
                // in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

                // In the optional fourth stage, we recursively walk the new structure, passing
                // each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
} ());

(function($) {
    $.fn.ellipsis = function(enableUpdating) {
        var s = document.documentElement.style;
        if (!('textOverflow' in s || 'OTextOverflow' in s)) {
            return this.each(function() {
                var el = $(this);
                if (el.css("overflow") == "hidden") {
                    var originalText = el.html();
                    var w = el.width();

                    var t = $(this.cloneNode(true)).hide().css({
                        'position': 'absolute',
                        'width': 'auto',
                        'overflow': 'visible',
                        'max-width': 'inherit'
                    });
                    el.after(t);

                    var text = originalText;
                    while (text.length > 0 && t.width() > el.width()) {
                        text = text.substr(0, text.length - 1);
                        t.html(text + "...");
                    }
                    el.html(t.html());

                    t.remove();

                    if (enableUpdating == true) {
                        var oldW = el.width();
                        setInterval(function() {
                            if (el.width() != oldW) {
                                oldW = el.width();
                                el.html(originalText);
                                el.ellipsis();
                            }
                        }, 200);
                    }
                }
            });
        } else return this;
    };
})(jQuery);

/**
* copy plugin
*
* Copyright (c) 2007 Yang Shuai (http://yangshuai.googlepages.com)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Use this plugin, you can copy the given text into
* clipboard in either ie or fx.
*
* @example $.copy('some text here');
* @desc Copy the string 'some text here' into clipboard.
*
*
* @param String t The text that will be copyed to clipboard.
*
* @author Yang Shuai/yangshuai@gmail.com
*/
jQuery.copy = function(t) {
    if (typeof t == 'undefined') {
        t = '';
    }
    d = document;
    if (window.clipboardData) {
        window.clipboardData.setData('Text', t);
    }
    else {
        var f = 'flashcopier';
        if (!d.getElementById(f)) {
            var dd = d.createElement('div');
            dd.id = f;
            d.body.appendChild(dd);
        }
        d.getElementById(f).innerHTML = '';
        var i = '<embed src="/_layouts/itn/scripts/jquery/plugins/copy.swf" FlashVars="clipboard=' + encodeURIComponent(t) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        d.getElementById(f).innerHTML = i;
    }
}