// JavaScript Document
jQuery.fn.toggleText = function(a, b) {
	return this.each(function() {
		jQuery(this).text(jQuery(this).text() == a ? b : a);
	});
};
/*
custom functions
*/
var site_root = 'http://' + document.location.hostname;
function url_query_parse(uqs){

	if(uqs == null)
		return {};
	var url_query_object = {};

	if(uqs.substring(0, 1)=='?')
		uqs = uqs.substring(1);
	if(uqs.substring(uqs.length-1)=='&')
		uqs = uqs.substring(0,uqs.length-1);

	var url_query_array = uqs.split('&');
	var key = ""; var val = "";
	for (var i=0;i<url_query_array.length;i++){
		key = url_query_array[i].split('=')[0];
		val = url_query_array[i].split('=')[1];
		url_query_object[key] = val;	
	}
	return url_query_object;
}
var url_variables = url_query_parse(window.location.href.split('#')[0].split('?')[1]);
function url_query_build(new_url_variables){

	if (new_url_variables != null && typeof(new_url_variables) == 'object')
	for (key in new_url_variables) {
		url_variables[key] = new_url_variables[key];
		if(new_url_variables[key] == null || new_url_variables[key].length == 0)
			delete url_variables[key];
	}
	var query_string = '';
	for (key in url_variables) {
		if(query_string.length > 0)
			query_string += '&';
		query_string += key+'='+url_variables[key];	
	}
	if(query_string.length > 0)
		query_string = '?'+query_string;

	return query_string;
}
function video_player(selector, file, autostart, pheight, pwidth, image_preview, swf_file, swf_skin){
	if(file == null || selector == null){ return null; }
	if(pheight == null){ var pheight = 200; }	
	if(pwidth == null){ var pwidth = 200; }
	if(image_preview == null) { var image_preview = ''; }
	if(autostart == null) { var autostart = 'false'; }
	$(selector).html('');
	
	// get file path data

	var flash_object = 
	{
		swf : swf_file,
		height : pheight,
		width : pwidth,
		params: {
			'allowfullscreen' : 'true',
			'allowscriptaccess' : 'always'
		},
		flashvars: {
			'subscribe' : 'true',
			'file' : file,
			'type' : 'video',
			'controlbar' : 'over',
			'autostart' : autostart,		
			'skin' : swf_skin,
			'image' : image_preview
		}
	};
	
	if(file.replace('rtmp://', '') != file){
		var file_array = file.split('/');
		flash_object['flashvars']['file'] = file_array[file_array.length-1];
		flash_object['flashvars']['streamer'] = file.replace(file_array[file_array.length-1], '');
	}
	
	$(selector).flash(flash_object);
}
function click_clear(selector){

	var default_string = $(selector).val();
	$(selector).each(function(){
	
		$(this).click(function(){
			if($(this).val() == default_string)
				$(this).val('');
		});
		$(this).blur(function(){
			if($(this).val().length == 0)
				$(this).val(default_string);
		});
	
	 });
	
}
click_clear('.click-clear');
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}
function email_valid(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}
function html_entity_decode(string) {

//return string.replace(/</g,"&lt;").replace(/>/g,">");
	return string.replace(/</g,"<").replace(/>/g,">");
}
function querylist(listname, soapenv, response){		

	if(listname == null && soapenv == null){
		return null;
	}
	if(soapenv == null){
		var soapenv =
			"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>" + listname + "</listName><viewFields><ViewFields></ViewFields></viewFields></GetListItems></soapenv:Body></soapenv:Envelope>";
	}
	
	if(response == null){
		response = 'raw';
	}
	
 	// Do the web service call async.
 	
	var xmlDoc = $.ajax({
		url: site_root + "/_vti_bin/lists.asmx",
			type: "POST",
			dataType: "xml",
			data: soapenv,
			async: false,
			contentType: "text/xml; charset=\"utf-8\""
	});

	if(response == 'text'){
		return xmlDoc.responseText;
	}
	
	if(response == 'array'){
		var rows = new Array(); var c = 0;
		$(xmlDoc.responseXML).find("z\\:row").each(function() {
			rows[c] = $(this);
			c=(c*1)+1;
		});
		
		return rows;
	}
	
	if(response == 'raw'){
		
		return xmlDoc;
	}	
}
function str_pad(string, length, character, side){
	

	if(!side){
		var side = 'l';
	}
	if(!length || !character || !string){
		return '';
	}

	string = string+'';
	while(string.length < length){
	
		if(side=='l'){
			string = character + ''+string;
		}
		if(side=='r'){
			string = ''+string + character;
		}
	
	}

	return string;
}
function substr_count (haystack, needle, offset, length) {
		var pos = 0, cnt = 0;

		haystack += '';
		needle += '';
		if (isNaN(offset)) {offset = 0;}
		if (isNaN(length)) {length = 0;}
		offset--;

		while ((offset = haystack.indexOf(needle, offset+1)) != -1){
				if (length > 0 && (offset+needle.length) > length){
						return false;
				} else{
						cnt++;
				}
		}

		return cnt;
}
function hide_login(domain){

	var href = window.location.href;
	href = href.replace('http://', '').replace('www.', '');
	domain = domain.replace('http://', '').replace('www.', '');
	href_array = href.split('/');
	href = href_array[0];

	if(href == domain){		
		$('#ctl00_explitLogout_ExplicitLogin').hide();
	}
}
function registerjs(){

	if(typeof(WPSC) == "undefined"){

		WPSC = new Object();
		WPSC.Init = function(){
		//do nothing
		}
		WPSC.WebPartPage = new Object();
		WPSC.WebPartPage.Parts = new Object();
		WPSC.WebPartPage.Parts.Register = function()
		{
		//do nothing
		}
	}
}
function loading_popup(input){
close_popup();
$(body_selector).append(
'<a class="make-block popup-base ajax-loading" id="popup-base" href="#" onclick="close_popup();return false;" title="Close Popup"></a>');
}
function open_popup(input){
close_popup();
$(body_selector).append(
'<a class="make-block popup-base" id="popup-base" href="#" onclick="close_popup();return false;" title="Close Popup"></a>'+
'<div class="popup" id="popup-container"><div id="popup-topbar"><a class="popup-close" href="#" onclick="close_popup();return false;">&times;</a></div><div id="popup-contents"></div></div>');

	var content = '';
	if($(input).length > 0){
		content = $(input).html();
		//$("#popup-close").width() =  $(input).width();
	}else{
		content = input;
	}

	$("#popup-contents").html(content);

	$('#popup-topbar').css({'width':$("#popup-contents").width()});
	
	var popup_base_height= $(document).height();
	$('.popup-base').css({'height':popup_base_height});

	$('.popup').css({
		//'margin-top' : '-'+(($('.popup').height())*1+10)/2+'px',
		'margin-left' : '-'+(($('.popup').width())*1+10)/2+'px'
	});
}
function close_popup(){
	$('#popup-base').remove();
	$('#popup-container').remove();
	$('#popup-content').html('');
}
function paginate(wrap, page_var, page_num, view_total, item){

// default vars	
	if(wrap == null){ return false;	}
	if(page_num == null){ page_num = 1;	}
	if(items == null){ var items = '.item'; }
	if(view_total == null){	
		var view_total = 15;
		if($(wrap+' input.max-items').length > 0 )
			var view_total = $(wrap+' input.max-items').val();
	}
	if(page_var == null)
		var page_var = $(wrap+' input.page-variable').val();
	
	var total_items = $(wrap+' input.total-items').val();

	if(view_total>total_items){ return false; }

	// hide if paginating and stop if not
	page_num = 1;
	if(url_variables[page_var] != null)
	page_num = url_variables[page_var];	
	url_variables[page_var] = null;
	
	var root_url = document.location.pathname.toLowerCase()+url_query_build(url_variables);
	if(url_query_build(url_variables).length > 0){
		root_url += '&'
	}else{
		root_url += '?'
	}

// set total pages
	var total_pages = 1;
	// count total pages
	var i = ((total_items/view_total)+'').split('.');
	total_pages = i[0];	
	if((total_items%view_total)>0){
		total_pages++;
	}

// start pagination
	var pagination = '<div class="rdiv pagination-wrap"><div class="rdiv pagination">';
	
	// add previous
	if(page_num>1){
		pagination +=
		'<a title="'+root_url+'" href="'+root_url+page_var+'='+(page_num-1)+'" class="prev-next prev">Previous</a>'
	}	

	// add page nums
	var page_count = 0;
	var selected = '';
	while(page_count<total_pages){
		page_count++;
		selected = '';
		if(page_count==page_num){
			selected = ' selected';
		}
		pagination +=
		'<a title="'+root_url+'" href="'+root_url+page_var+'='+page_count+'" class="num'+selected+'">'+page_count+'</a>'	
	}

	if(page_num<total_pages){
		pagination +=
		'<a title="'+root_url+'" href="'+root_url+page_var+'='+((page_num*1)+1)+'" class="prev-next next">Next</a>';
	}

	pagination += '</div></div><div class="rdiv pagination-footer"></div>';
	
	$(wrap).append(pagination);
	$(document).ready(function() {
		center_this(wrap+' .pagination');
	});
}
function center_this(selector){
	if(selector == null){
		return false;
	}
	$(selector).css({
		'width':'auto'
	});
	var w = $(selector).width();
	$(selector).css({
		'float':'none',
		'margin':'0 auto',
		'width':w
	});	
}
function abbreviate(selector, maxlength){
			
	//if($.browser.msie) return false;
	if(maxlength == null)
		maxlength = 250;

	var i = 0;
	$(selector).each(function(){ i++;

		var html = $(this).html();
		var text = $(this).text();
		if(text.length < maxlength)
			return true;

		$(this).attr({'id':$(this).attr('id')+'undefined'});		
		if($(this).attr('id') == 'undefined')
			$(this).attr({'id':'abbreviate-'+(new Date().getTime()) + i});
		var id = $(this).attr('id');
		
		$(this).before()
		$(this).empty();
		
		var abbreviated = 
		(text.substring(0, maxlength)+'...').replace(' ...','...');
		
		$(this).html(
		'<span class="abbreviated">' + abbreviated + '</span> \
		<a href="#" class="read-more">read more</a> \
		<span class="unabbreviated" \
			style="display: none;">'+html+'</span> \
			<a href="#" class="read-less">read less</a>');
		$('#'+id+' .read-less').hide();
		
		$('#'+id+' .read-more').click(function(){
			$(this).hide();
			$('#'+id+' .read-less').show();
			$('#'+id+' .abbreviated').hide();	
			$('#'+id+' .unabbreviated').show();
			return false;
		});
		$('#'+id+' .read-less').click(function(){
			$(this).hide();
			$('#'+id+' .read-more').show();
			$('#'+id+' .abbreviated').show();	
			$('#'+id+' .unabbreviated').hide();
			return false;
		});
	});
}
function reset_position(selector){
	$(selector).css('position','relative');
	$(selector).css('position','absolute');	//$(selector).css({'position':'relative','display':'inline-block'});
}
function hover_opacity(selector, amount){
	if($(selector).length == 0)
		return false;		
	$(selector).hover(function(){	
		$(this).css('opacity', amount);
	},function(){	
		$(this).css('opacity', 1.0);	
	});
}
function testthis(input){
	if(input == null) return false;
	if($('#test-this').length == 0)
		$('#body-tag').prepend('<div id="test-this" style="background-color: #fff; border-bottom: #464646 solid 1px; padding: 10px;"></div>');
	$('#test-this').append(input+'<br/>');
}
function height_100(){
	if($('.height-100').length == 0) return false;
	$('.height-100').each(function(){
		$(this).css({'height':$(this).parent().height()+'px'});		
		$(this).css({'background-position':'bottom right'});				  
	});
}
function page_body_table(){

	if($('.page-body .table').length == 0) return false;
	$('.page-body .table tr td').each(function(){
		$(this).removeClass('thead');
		$(this).removeClass('even');
	});
	$(".table tr:first td").addClass('thead');
	$('.page-body .table tr:nth-child(even) td').addClass('even');
	$('.page-body .table').each(function(){
		$(this).css({'height':'auto','width':'100%'});
	});
}
function drop_down_links(){

	var i = 1;

	$('ul.drop-down').each(function(){
		$(this).attr({'id':'drop-down-'+i});
		$('#drop-down-'+i+' li:first').addClass('first');
		$(this).parent().attr({'id':'drop-down-parent-'+i});
		i++;
	});

	$('ul.drop-down').hover(function(){
		$(this).show();
		
	},function(){
		var psid = 
			'#'+$(this).attr('id').replace('drop-down-', 'drop-down-parent-');
		$(this).hide();
	});

	$('ul.drop-down').parent().hover(function(){
		var sid = '#'+$(this).attr('id').replace('drop-down-parent-','drop-down-');
		$(sid).css({
			'display':'block',
			'width':$(this).width()+'px',
			'top':($(this).height()-2)+'px',
			'padding-top':'2px',
			'left':($(this).offset().left - $(this).parent().offset().left)+'px'
		});

	},function(){
		var sid = '#'+$(this).attr('id').replace('drop-down-parent-','drop-down-');
		$(sid).hide();		
	});	

}
function go_to(raw_address, query){
	
	var new_url_variables = url_variables;

	if(raw_address== null)
		raw_address= document.location.href;
	
	var address = raw_address.split('#')[0].split('?')[0];
	var aname = "";
	if(raw_address.split('#')[1] != null)
		aname = raw_address.split('#')[1];

	if(typeof(query)=='string'){
		new_url_variables = url_query_parse(query);
	}else if(typeof(query)=='object'){
		new_url_variables = query;
	}else{
		new_url_variables = {};
	}
	
	query = url_query_build(new_url_variables);
	new_href = address+query+aname;
	window.location = new_href.replace('??','?');
	return false;
}
function print_preview(){

	$('#body-tag').hide();
	$('#body-tag').html('<div id="printables" class="rdiv printables"><div class="rdiv print-hide normal-view"><a href="#" onclick="go_to(null,\'print=\'); return false;">Return to Normal View</a></div></div><div id="non-printables" class="hidden">'+$('#body-tag').html()+'</div>');
	$('#body-tag').css({'background':'none #fff'});
	
	if($('#print-header').length > 0)
		$('#printables').append('<div class="rdiv print-header">'+$('#print-header').html()+'</div>');

	if($('#print-body').length > 0)
		$('#printables').append('<div class="rdiv print-body">'+$('#print-body').html()+'</div>');

	if($('#print-footer').length > 0)
		$('#printables').append('<div class="rdiv print-footer">'+$('#print-footer').html()+'</div>');
	
	
	$('#body-tag').show();


}
function print_preview_off(){

	if($('#non-printables').length == 0)
		return false;
	
	var href = window.location.href.replace("?print=yes&","?").replace("?print=yes","");
	if(href != window.location.href){
		window.location = href;
		return false;
	}
	$('#body-tag').hide();
	$('#printables').remove();
	var swaphtml = $('#non-printables').html();
	$('#non-printables').remove();
	$('#body-tag').html(swaphtml);
	$('#body-tag').show();
	
	
}
if (typeof btoa == 'undefined') {
    function btoa(str) {
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        var encoded = [];
        var c = 0;
        while (c < str.length) {
            var b0 = str.charCodeAt(c++);
            var b1 = str.charCodeAt(c++);
            var b2 = str.charCodeAt(c++);
            var buf = (b0 << 16) + ((b1 || 0) << 8) + (b2 || 0);
            var i0 = (buf & (63 << 18)) >> 18;
            var i1 = (buf & (63 << 12)) >> 12;
            var i2 = isNaN(b1) ? 64 : (buf & (63 << 6)) >> 6;
            var i3 = isNaN(b2) ? 64 : (buf & 63);
            encoded[encoded.length] = chars.charAt(i0);
            encoded[encoded.length] = chars.charAt(i1);
            encoded[encoded.length] = chars.charAt(i2);
            encoded[encoded.length] = chars.charAt(i3);
        }
        return encoded.join('');
    }
}

if (typeof atob == 'undefined') {
    function atob(str) {
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        var invalid = {
            strlen: (str.length % 4 != 0),
            chars:  new RegExp('[^' + chars + ']').test(str),
            equals: (/=/.test(str) && (/=[^=]/.test(str) || /={3}/.test(str)))
        };
        if (invalid.strlen || invalid.chars || invalid.equals)
            throw new Error('Invalid base64 data');
        var decoded = [];
        var c = 0;
        while (c < str.length) {
            var i0 = chars.indexOf(str.charAt(c++));
            var i1 = chars.indexOf(str.charAt(c++));
            var i2 = chars.indexOf(str.charAt(c++));
            var i3 = chars.indexOf(str.charAt(c++));
            var buf = (i0 << 18) + (i1 << 12) + ((i2 & 63) << 6) + (i3 & 63);
            var b0 = (buf & (255 << 16)) >> 16;
            var b1 = (i2 == 64) ? -1 : (buf & (255 << 8)) >> 8;
            var b2 = (i3 == 64) ? -1 : (buf & 255);
            decoded[decoded.length] = String.fromCharCode(b0);
            if (b1 >= 0) decoded[decoded.length] = String.fromCharCode(b1);
            if (b2 >= 0) decoded[decoded.length] = String.fromCharCode(b2);
        }
        return decoded.join('');
    }
}
function form_page_variable(selector){

	if($(selector).length < 1) return false;
	$(selector+' input.input').keypress(function(event) {
		if (event.keyCode == '13') {
			window.location =
			site_root+ 
			$(selector+' input.page-var').val() + 
			$(selector+' input.input').val();
			return false;
		}
	});
	$(selector+' .submit').click(function(){
		window.location =
			site_root+ 
			$(selector+' input.page-var').val() + 
			$(selector+' input.input').val();
		return false;
	});

}
