﻿var IDMUtilsJS_Loaded = true;
String.prototype.endsWith = function (t) 
{ 
	return (t == this.substring(this.length - t.length));
};

/*
====================================================================
== formatDate(date, formatString) ==================================
====================================================================

These are the parts of the format string - similar to C#
but not quite.

Field        | Full Form          | Short Form
-------------+--------------------+-----------------------
Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
             | NNN (abbr.)        |
Day of Month | dd (2 digits)      | d (1 or 2 digits)
Day of Week  | EE (name)          | E (abbr)
Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
Minute       | mm (2 digits)      | m (1 or 2 digits)
Second       | ss (2 digits)      | s (1 or 2 digits)
AM/PM        | a                  |

NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
Examples:
 "MMM d, y" matches: January 01, 2000
                     Dec 1, 1900
                     Nov 20, 00
 "M/d/yy"   matches: 01/20/00
                     9/2/00
 "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
------------------------------------------------------------------
*/

var MONTH_NAMES=['January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var DAY_NAMES=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
function LZ(x){return(x<0||x>9?"":"0")+x}function formatDate(dt,fmt){fmt=fmt+"";var r="";var i_fmt=0;var c="";var token="";var y=dt.getYear()+"";var M=dt.getMonth()+1;var d=dt.getDate();var E=dt.getDay();var H=dt.getHours();var m=dt.getMinutes();var s=dt.getSeconds();var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;var v=new Object();if(y.length<4){y=""+(y-0+1900)}v["y"]=""+y;v["yyyy"]=y;v["yy"]=y.substring(2,4);v["M"]=M;v["MM"]=LZ(M);v["MMM"]=MONTH_NAMES[M-1];v["NNN"]=MONTH_NAMES[M+11];v["d"]=d;v["dd"]=LZ(d);v["E"]=DAY_NAMES[E+7];v["EE"]=DAY_NAMES[E];v["H"]=H;v["HH"]=LZ(H);if(H==0){v["h"]=12}else if(H>12){v["h"]=H-12}else{v["h"]=H}v["hh"]=LZ(v["h"]);if(H>11){v["K"]=H-12}else{v["K"]=H}v["k"]=H+1;v["KK"]=LZ(v["K"]);v["kk"]=LZ(v["k"]);if(H>11){v["a"]="PM"}else{v["a"]="AM"}v["m"]=m;v["mm"]=LZ(m);v["s"]=s;v["ss"]=LZ(s);while(i_fmt<fmt.length){c=fmt.charAt(i_fmt);token="";while((fmt.charAt(i_fmt)==c)&&(i_fmt<fmt.length)){token+=fmt.charAt(i_fmt++)}if(v[token]!=null){r=r+v[token]}else{r=r+token}}return r};

function IDMTextBoxKeyPress(e, btnID)
{
	var k = e.which ? e.which : e.keyCode;
	if(k == 13)
	{
		if(btnID != '')
		{
			var btn = document.getElementById(btnID);
			var tagName = btn.tagName.toUpperCase();
			if(tagName == 'INPUT')
			{
				// this does not work with a imagebutton which has no click() event
				// TODO: find a fix/workaround for this problem.
				btn.click();
			}
			else if(tagName == 'A')
			{
				document.location.href = btn.href;
			}
		}
		return false;
	}
	else
	{
	    return true;
	}
}

// Usage: String.format("Tell me the {0}!", "score");
String.format = function()
{
    if( arguments.length == 0 )
        return null;

    var str = arguments[0];
    for(var i=1;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

// Make call on event or end of dom load... otherwise a js error will happen.
function SetFocus(sElemID)
{
    var focusElem = document.getElementById(sElemID);
    if(focusElem)
        focusElem.focus();
}

// Attach this to the onkeypress event of textbox, and/or onmouseup of button.
function CheckIfValidAction(evt) 
{
    var evt             = (evt) ? evt : event;
    this.objTarget      = (evt.target) ? evt.target : evt.srcElement;
    this.charCode       = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
    this.isButtonEvent  = ((this.objTarget.type=="button") || (this.objTarget.type=="submit"))? true : false;
    this.isLinkEvent    = (this.objTarget.type=="link") ? true : false;
    this.isKeyEvent     = (!this.isButtonEvent);
    this.isActionValid  = false;
    if(this.isButtonEvent || (this.charCode == 13)) {
        this.isActionValid = true;
    }
}

function IDMStoryPhoto(cid, index)
{
	var url = '/Photo.aspx?content_id=' + cid;
	if(index)
		url += '&i=' + index;
	window.open(url,'PhotoViewer','status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,width=740,height=610');
}

function IDMSlideshowPhoto(sid, pid)
{
	var url = '/Photo.aspx?slideshow=' + sid;
	if(pid)
		url += '&photo=' + pid;
	window.open(url,'PhotoViewer','status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,width=740,height=610');
}

function IDMUGCPhoto(uid, index)
{
	var url = '/Photo.aspx?ugc=' + uid;
	if(index)
		url += '&i=' + index;
	window.open(url,'PhotoViewer','status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,width=740,height=610');
}

function IDMMap(cid, mid) {
	var url = '/Map.aspx?content_id=' + cid + '&map=' + mid;
	window.open(url, 'MapViewer', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,width=740,height=610');
}

function _LinkPrefetch()
{
	if(document.getElementsByTagName && navigator.userAgent.indexOf('MSIE')>=0)
	{
		var links = document.getElementsByTagName('link');
		for (var i = 0; i < links.length; i++)
		{
			var link = links[i];
			if(link.rel && link.rel=="prefetch" && link.href && link.href.length>0)
			{
				var img = new Image();
				img.src = link.href;
			}
		}
	}
}

function LinkPrefetchInit()
{
	setTimeout("_LinkPrefetch();",250);
}

function OnCharsLeft(box, lbl, max)
{
	if(box !=null && box.value != null) 
	{
		if (box.value.length > max)
		{
			alert("Text may not exceed " + max +" characters in length.");
			box.value = box.value.substring( 0, max);
		} 
		var c = max - box.value.length;
		lbl.innerHTML = c.toString() + ' characters remaining';
	}
}

function InitCharsLeft(boxid, lblid, max)
{
	var box = document.getElementById(boxid);
	var lbl = document.getElementById(lblid);
	box.onkeyup = function () { return OnCharsLeft(box, lbl, max); };
	OnCharsLeft(box, lbl, max);
}

var _ieTempCss;
var _ffTempCss;

function TempCss(selector, declaration) 
{
	if(_ieTempCss == null && _ffTempCss == null)
	{
		var ua = navigator.userAgent.toLowerCase();
		var isIE = (/msie/.test(ua)) && !(/opera/.test(ua)) && (/win/.test(ua));
		var style_node = document.createElement("style");
		style_node.setAttribute("type", "text/css");
		style_node.setAttribute("media", "screen");
		document.getElementsByTagName("head")[0].appendChild(style_node);
		if(!isIE)
			_ffTempCss = style_node;
		else
		{
			var ss = document.styleSheets[document.styleSheets.length - 1];
			if (typeof(ss.addRule) == "object")
				_ieTempCss = ss;
		}
	}
	var dec = selector + " {" + declaration + "}  ";
	try {
		if (_ffTempCss != null)
			_ffTempCss.innerHTML += dec;
		else if (_ieTempCss != null)
			_ieTempCss.cssText += dec;
	}
	catch (err) { }
}

function RevertTempCss() {
	try {
		if (_ffTempCss != null)
			_ffTempCss.innerHTML = '';
		else if (_ieTempCss != null)
			_ieTempCss.cssText = '';
	} catch (Error) { }
}

function ShowModal(id)
{
	TempCss('object', 'visibility:hidden;');
	TempCss('embed', 'visibility:hidden;');
	$find(id).show();
	return false;
}

function HideModal(id)
{
	RevertTempCss();
	$find(id).hide();
	return false;
}

function IDMDoCallback(targetID, eventArgument, feedbackID, waitingText)
{
	if(waitingText)
		document.getElementById(feedbackID).innerHTML = waitingText;
	WebForm_DoCallback(targetID,eventArgument,IDMCallbackComplete,feedbackID,IDMCallbackError,true);
}

function IDMCallbackComplete(result, feedbackID)
{
	document.getElementById(feedbackID).innerHTML = result;
}

function IDMCallbackError()
{
	alert('An error occurred trying to communicate with the server.');
}

function ClickOnce(btn, doVal, msg) {
	if (doVal && typeof(Page_ClientValidate) == 'function')
	{
		if (Page_ClientValidate() == false) { return false; }
	}
	if (!msg || (msg=='undefined'))
		msg = btn.value;
	btn.value = msg;
	btn.disabled = true;
	if(btn.className == 'Button')
		btn.className = 'ButtonDisabled';
	return true;
}

function GetScroll()
{
	if(typeof(window.pageYOffset) != 'undefined')
		return window.pageYOffset;
	else if(typeof(document.documentElement.scrollTop) != 'undefined' && document.documentElement.scrollTop > 0)
		return document.documentElement.scrollTop;
	else if(typeof(document.body.scrollTop) != 'undefined')
		return document.body.scrollTop;
}

function SetScroll(scroll)
{
	if(typeof(document.documentElement.scrollTop) != 'undefined' && document.documentElement.scrollTop >= 0)
		document.documentElement.scrollTop = scroll; 
	else if(typeof(document.body.scrollTop) != 'undefined')
		document.body.scrollTop = scroll;
	else if(typeof(window.pageYOffset) != 'undefined')
		window.pageYOffset = scroll;
	document.body.scrollTop = scroll; // Safari
}

function GetWinHeight()
{
	if(typeof(window.innerHeight) == 'number')
		return window.innerHeight;
	else if(document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	else if(document.body && document.body.clientHeight)
		return document.body.clientHeight;
}

function GetRectById(id) 
{
	var obj = document.getElementById(id);
	return GetRect(obj);
}

function GetRect(obj) 
{
	var w = (obj.offsetWidth)?obj.offsetWidth:obj.style.pixelWidth;
	var h = (obj.offsetHeight)?obj.offsetHeight:obj.style.pixelHeight;
	var l=0, t=0;
	if (obj.offsetParent) {
		do {
			l += obj.offsetLeft;
			t += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return {"left":l,"top":t,"width":w,"height":h,"right":l+w,"bottom":t+h};
}

function ScrollToId(id, topExtra, bottomExtra)
{
	ScrollToObject(document.getElementById(id), topExtra, bottomExtra);
};

function ScrollToObject(obj, topExtra, bottomExtra)
{
	var rect = GetRect(obj);
	if(topExtra) {rect.top -= topExtra; rect.height += topExtra; }
	if(bottomExtra) {rect.bottom += bottomExtra;; rect.height += topExtra; }
	var scrollTop = GetScroll();
	var scrollHeight = GetWinHeight();
	if(rect.top<scrollTop)
		SetScroll(rect.top);
	else if(rect.bottom>(scrollTop+scrollHeight))
		SetScroll(rect.bottom-scrollHeight);
}

function JSWL(str)
{
	document.writeln(str);
}

function ReadCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function ReadSubCookie(name,key)
{
	key += '=';
	var c = ReadCookie(name);
	if(c)
	{
		var s = c.split('&');
		for(var i=0;i<s.length;i++)
		{
			if(s[i].indexOf(key)==0)return s[i].substring(key.length,s[i].length);
		}
	}
	return null;
}
	
function SetCookie(cookieName,value,mins,path) 
{
	if(path == 'auto')
		path = document.location.pathname;
	if (mins && mins != 0) {
		var dt = new Date();
		dt.setTime(dt.getTime()+(mins*60*1000));
		var exp = dt.toGMTString();
	}
	var dc = cookieName + "=" +escape( value ) +
		((exp)?";expires="+exp:"")+
		((path)?";path="+path:"");
	document.cookie = dc;
}

function UnsetCookie(name)
{
	createCookie(name,"",-1);
}

function HtmlWriter()
{
	this.buf = '';
	this.write = function (txt)
	{
		this.buf += txt;
	};
	this.writeln = function (txt)
	{
		this.buf += txt + '\n';
	};
	this.toString = function ()
	{
		return this.buf;
	};
}

function IDMHitCount(host,id,type)
{
	var cn = 'HitCount_'+id+'_'+type;
	var cv = ReadCookie(cn);
	if(cv == '1')
		return;
	
	SetCookie(cn, '1', 0, 'auto');
	JSWL('<img src="http://'+host+'/script/HitCounter.ashx?id='+id+'&type='+type+'" width="1" height="1" style="display:none;" />');
}

var _uts = 12;
function UserTextSize(size)
{
	var tag = document.getElementById('UserTextSize');
	if(tag)
	{
		if(size>10) _uts = size;
		else if(ReadCookie('uts'))
			_uts = ReadCookie('uts');
		SetCookie('uts',_uts,525600);
		for(var i=0; i<document.styleSheets.length; i++)
		{
			var ss = document.styleSheets[i];
			if(ss.id == 'UserTextSize' || ss.title == 'UserTextSize')
			{
				var mr = new Array();
				if(ss.cssRules)
					mr = ss.cssRules;
				else if(ss.rules) 
					mr = ss.rules;
				if(mr[0])
					mr[0].style.fontSize = _uts + 'px';
			}
		}
	}
}
UserTextSize(0);

function RegTextSizeControl(id,addEvts)
{
	var sizes = [11,12,14,16];
	var btns = new Array();
	for(var i=0;i<sizes.length;i++)
	{
		var s = sizes[i];
		var bID = id + '_' + s;
		var btn = document.getElementById(bID);
		if(addEvts)
		{
			$addHandler(btn,'mouseover', TextSizeEvent);
			$addHandler(btn,'mouseout', TextSizeEvent);
			$addHandler(btn,'click', TextSizeEvent);
		}
		var ext = (_uts == s) ? 'S.gif' : 'N.gif';
		btn.src = btn.src.substr(0, btn.src.length - 7) + s + ext;
	}
}

function TextSizeEvent(arg)
{
	var btn = arg.target;
	var id = btn.id;
	var isize = parseInt(id.substr(id.length-2));
	if(arg.type == 'click')
	{
		UserTextSize(isize);
		RegTextSizeControl(id.substr(0, id.length-3));
	}
	var ext = '';
	var isS = (_uts == isize);
	if(arg.type == 'mouseout')
		ext = isS ? 'S.gif' : 'N.gif';
	else if(arg.type == 'mouseover')
		ext = 'H.gif';
	if(ext != '')
		btn.src = btn.src.substr(0, btn.src.length - 7) + isize + ext;
}

function GetTimerEnabled(timerClientID)
{
	return $find(timerClientID).get_enabled();
}

function SetTimerEnabled(timerClientID,state)
{
	var t=$find(timerClientID);
	var prevState=t.get_enabled();
	t._update(state, t.get_interval());
	return prevState;
}

function IDMTextBoxSaveText(tb_id, cookie_id, expire) {
    var cookieval = document.getElementById(tb_id).value;
    if (expire <= 0)
        document.cookie = cookie_id + "=" + cookieval;
    else {
        var expireDate = new Date;
        expireDate.setDate(expireDate.getDate() + expire);
        document.cookie = cookie_id + "=" + cookieval + ";expires=" + expireDate.toGMTString();
    }
}

function IDMDropDownSaveIndex(tb_id, cookie_id, expire) {
    var cookieval = document.getElementById(tb_id).selectedIndex;
    if (expire <= 0)
        document.cookie = cookie_id + "=" + cookieval;
    else {
        var expireDate = new Date;
        expireDate.setDate(expireDate.getDate() + expire);
        document.cookie = cookie_id + "=" + cookieval + ";expires=" + expireDate.toGMTString();
    }
}

function SetAutoRefresh(seconds) {
    setTimeout('SafeAutoRefresh();', seconds * 1000);
}

function SafeAutoRefresh() {
	window.location.href = window.location.href;
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();