/* Mdc Global Functions */
var timeoutMsg="The request timed out, please try again.";
var cancelRequestMsg="The request has been canceled.";

jQuery.mdc={
PREVIOUS_PAGE_COOKIE_NAME:"PreviousPage"
,HOME_PAGE_URL:"/Pages/default.aspx"
,TYPE_AHEAD_COOKIE_NAME:"typeAheadUrl"
,LOGOUT_COUNTDOWN_CALLBACK:null
,createForm:function(theAction,theFormType){return $('<form></form>').attr('name','mdcNewForm').attr('method',theFormType).attr('action',theAction);}
,createHiddenField:function(theName,theValue){var aHiddenField=$('<input type="hidden" name="'+theName+'" />');aHiddenField.val(theValue);return aHiddenField[0];}
,submitForm:function(theAction,theMethod,theArguments){
	var aForm=this.createForm(theAction,theMethod);
	for(var i=1;i<theArguments.length;i++){
		var aValue=$('#'+theArguments[i]).attr('type')=='checkbox'?$('#'+theArguments[i])[0].checked:$('#'+theArguments[i]).val();
		aForm.append(this.createHiddenField(theArguments[i],aValue));
	}
	aForm.appendTo($(document.body)).submit();}
,submitGetForm:function(theAction){this.submitForm(theAction,"GET",arguments);}
,submitQuickSearch:function(theAction,theMethod,theArguments){
var anAction = "/QuickSearch~/";
	for(var i=1;i<theArguments.length;i++){
		var aValue=$('#'+theArguments[i]).attr('type')=='checkbox'?$('#'+theArguments[i])[0].checked:$('#'+theArguments[i]).val();
		anAction +=aValue + "/";
	}
	anAction +="qs";
    var aForm=this.createForm(anAction,theMethod);
	aForm.appendTo($(document.body)).submit();}
,submitGetQuickSearch:function(theAction){this.submitQuickSearch(theAction,"GET",arguments);}
,submitPostForm:function(theAction){this.submitForm(theAction,"POST",arguments);}
,validateSearchTerm:function(theSearchInput){if((theSearchInput).attr('value')=='Search entire site') $(theSearchInput).attr('value', '');return true;}
,validateSearchWithinResultsTerm:function(theSearchInput){if((theSearchInput).attr('value')=='Search within results') $(theSearchInput).attr('value', '');return true;}
,encodeUrl:function(theUrl){if(typeof encodeURIComponent=="function") return encodeURIComponent(theUrl);return escape(theUrl);}
,searchWithinSearch:function(theSearchUrl){document.location=theSearchUrl+this.encodeUrl((theSearchUrl.charAt(theSearchUrl.length-1)=='='?"":"|")+$("#mdcSearchWithinSearchText").val());}
,searchWithinSearchTop:function(theSearchUrl){if($("#mdcSearchWithinSearchTextTop").attr("value") == "") document.location=theSearchUrl;else document.location=theSearchUrl+this.encodeUrl((theSearchUrl.charAt(theSearchUrl.length-1)=='='?"":"|")+$("#mdcSearchWithinSearchTextTop").val());}
,searchWithinSearchRR:function(){ if($("#mdcSearchWithinSearchTextRR").attr("value") == "") document.location = document.location; else {var location = ""+document.location; document.location +=(((location.indexOf("kw")==-1)?"?kw=":"|")+$("#mdcSearchWithinSearchTextRR").val());}}
,RemoveWithInSearchItem:function(theSearchItem){ var local = ""+document.location; var pos=local.indexOf("?kw="); if(pos!=-1){var orgurl=local.substr(0,pos); var orgkws=local.substr(pos+4); var newkws="?kw="; var tmpos = orgkws.indexOf("|"); while(tmpos!=-1){var tpkw=orgkws.substr(0,tmpos); if(tpkw!=theSearchItem) newkws+=(tpkw+"|"); orgkws=orgkws.substr(tmpos+1);tmpos=orgkws.indexOf("|"); if((tmpos==-1)&&(orgkws!=theSearchItem))newkws+=(orgkws+"|");} newkws = newkws.substr(0, newkws.length-1);document.location=orgurl+(newkws.length<4?"":newkws);}}
,tryAnotherSearch:function(theSearchUrl){document.location=theSearchUrl+this.encodeUrl($("#mdcTryAnotherSearchText").val());}
,typeAhead:function(theEvent,theSearchKey){
	if(theEvent.which == 27) {
		$.mdc.typeAheadIndex=-1;
		$("#mdcTypeAheadContainer a").removeClass('mdcTypeAheadSelected');
		return;
	} 
	if(theEvent.which != 38 && theEvent.which != 40){
		if(theSearchKey.length >=3) {
			var url = '/page/typeahead.aspx?tt='+this.encodeUrl(theSearchKey);
			this.microsoftAjax(url,"GET",function(theReturnHtml,textStatus)
			{
                    var aStartIndex=theReturnHtml.search("<div id=\"mdcTypeAheadContainer\"")
		   			var aEndIndex=theReturnHtml.search("</body>")
		            if(aStartIndex==-1){
		       			$("#mdcTypeAheadSpace").html("");
            			$("#mdcTypeAheadSpace, #mdcTypeAheadSpaceBottom, #mdcTypeAheadSpaceRight").addClass('mdcHide');
		       		} else {
		       			$("#mdcTypeAheadSpace").html(theReturnHtml.substring(aStartIndex,aEndIndex));
		                $("#mdcTypeAheadSpace, #mdcTypeAheadSpaceBottom, #mdcTypeAheadSpaceRight").removeClass('mdcHide');
			   		}
					$('#mdcTypeAheadContainer tr').click(function(){$.mdc.pushPreviousPageCookie();document.location=$(this).find("td").children().eq(0).val();});
					$('#mdcTypeAheadContainer tr').hover(function(){$(this).addClass('mdcTypeAheadSelected');},function(){$(this).removeClass('mdcTypeAheadSelected');});
		        	$('#mdcTypeAheadSpace').prepend('<iframe scrolling="no" frameborder="0"/>');
		        	$('#mdcTypeAheadSpace iframe').height($('#mdcTypeAheadSpace').height()).width($('#mdcTypeAheadSpace').width());
		        	$('#mdcTypeAheadSpaceBottom').css('top',$('#mdcTypeAheadSpace').position().top+$('#mdcTypeAheadSpace').height()).width($('#mdcTypeAheadSpace').width()-8);
		        	$('#mdcTypeAheadSpaceRight').css('left',$('#mdcTypeAheadSpace').position().left+$('#mdcTypeAheadSpace').width()).height($('#mdcTypeAheadSpace').height());
			});
		} else {
			$('#mdcTypeAheadSpace').html('');
			$("#mdcTypeAheadSpace, #mdcTypeAheadSpaceBottom, #mdcTypeAheadSpaceRight").addClass('mdcHide');
		}
	}
}
,microsoftAjax: function(url,type,successCallback)
{
$.ajax({
 url: url,
 type: type,
 cache: false,async:true,
 success: function(html,textStatus){
       var regExp=/^\d+\|pageRedirect\|\|(.+)\|$/;
       var match=regExp.exec(html);
       if(match==null)
       {
           successCallback(html,textStatus);
       }
       else
       {
       		$('#mdcTypeAheadSpace').html('');
			$("#mdcTypeAheadSpace").addClass('mdcHide');
       }
 },
 beforeSend:function (request) {
 request.setRequestHeader("X-MicrosoftAjax", "Delta=true");
    }
});
}
,readCookie:function(theCookieName){
	var aCookie=""+document.cookie;
	var aFirstIndex=aCookie.indexOf(theCookieName+"=");
	if(aFirstIndex==-1||theCookieName=="") return "";
	var aEndIndex=aCookie.indexOf(';',aFirstIndex);
	if(aEndIndex==-1) aEndIndex=aCookie.length; 
	return aCookie.substring(aFirstIndex+theCookieName.length+1,aEndIndex);}
,writeCookie:function(theCookieName,theCookieValue){
	var aExpireTime = new Date(new Date().getTime()+1000*60*30);
	document.cookie=theCookieName+ "=" + theCookieValue + ";expires=" + aExpireTime.toGMTString() + ";path=/";}
,pushPreviousPageCookie:function(){
	var aCookieValueArray=this.readCookie(this.PREVIOUS_PAGE_COOKIE_NAME).split("__",9);
	if(aCookieValueArray.length==1 && aCookieValueArray[0].length==0) {
		aCookieValueArray=[this.encodeUrl(window.location.pathname+window.location.search)];
	}else{
		aCookieValueArray=[this.encodeUrl(window.location.pathname+window.location.search)].concat(aCookieValueArray);
	}
	this.writeCookie(this.PREVIOUS_PAGE_COOKIE_NAME,aCookieValueArray.join("__"));}
,clearPreviousPageCookie:function(){
	var aCookieValueArray=this.readCookie(this.PREVIOUS_PAGE_COOKIE_NAME).split("__");
	this.writeCookie(this.PREVIOUS_PAGE_COOKIE_NAME,aCookieValueArray.slice(1).join("__"));}
,researchShowAllChangeFilter:function(theSelect){
	var aIndex=theSelect.selectedIndex;
	var aRequestUrl=theSelect.options[aIndex].value;
	document.location=aRequestUrl;}
,setLoginErrorMessage:function(theMessage){$("#mdcLoginErrorMsgControl").html(theMessage);$('#mdcLoginErrorMsgControl').removeClass('mdcHide');}
,validateLogin:function(){
 	var isNameValidate=true;
	if(!$('#mdcUserNameWrap>input').val()) {$('#UserNameRequired').css('visibility','visible');isNameValidate=false;}
	if(isNameValidate) $('#UserNameRequired').css('visibility','hidden');
	var isPasswordValidate=true;
	if(!$('#mdcPasswordWrap>input').val()) {$('#PasswordRequired').css('visibility','visible');isPasswordValidate=false;}
	if(isPasswordValidate) $('#PasswordRequired').css('visibility','hidden');
    if(isNameValidate&&isPasswordValidate) {
        $('#mdcLoginErrorMsgControl').addClass('mdcHide')
    }
    else {
        this.setLoginErrorMessage('A User name and password are required for access to Moodys.com');
    }
    return isNameValidate&&isPasswordValidate;
}
,timeOutRedirect:function(theRedirectUrl,theIndicator){var theSecond=theIndicator.text();theSecond--;if(theSecond<0){clearInterval($.mdc.LOGOUT_COUNTDOWN_CALLBACK); document.location=theRedirectUrl;} else {theIndicator.text(theSecond+'');}}
,mdcPopup:function(theUrl)
	{
		newwindow=window.open(theUrl,'','height=400,width=150,scrollbars=1,resizable=1',0); 
		if (window.focus) {newwindow.focus()}; 
		return false;
	}
,CheckChecked:function(theHiddenInput,theList){
	var aCheckValue='';
	theList.find('input:checked').each(function(){aCheckValue=aCheckValue==''?$(this).next().val():aCheckValue+";"+$(this).next().val();});
	theHiddenInput.val(aCheckValue);
}
};
/* Mdc Function Plugins */
jQuery.fn.extend({
mdcImgHover:function(){this.attr('src',this.attr('src').replace(/O(ff|n)/,'Over'));}
,mdcImgOff:function(){this.attr('src',this.attr('src').replace(/Over/,'Off'));}
,mdcImgOn:function(){this.attr('src',this.attr('src').replace(/Over/,'On'));}
,mdcImgOut:function(){if(this.hasClass('mdcSelected')){this.mdcImgOn();} else {this.mdcImgOff();}}
,mdcInsertSeperatorImg:function(theImgName){this.children(':not(input)').filter(':visible').slice(1).before('<img class="mdcImgSeperator" src="images/' + theImgName + '"/>');}
,mdcInsertShowMore:function(theTriggerCount){
	this.each(function() {
		var aChildList=$(this).children('li');
		if(aChildList.length>(theTriggerCount+2)){
			aChildList.slice(theTriggerCount).addClass('mdcMoreItem');
			aChildList.filter(':last').css('display','block');
		}
	});
}
,mdcShowMore:function(){
	this.parent().toggleClass('mdcExpanded');
	if(this.parent().hasClass('mdcExpanded')) {
		this.html('<span>Show Less</span>');
	} else {
		this.html('<span>Show All</span>');
	}
}
,mdcCheckLastTab:function(theCheckSize){if(this.length==theCheckSize) this.filter(':last').addClass('mdcTabLastItem');}
,mdcTriggerButtonClickInput:function(theButton,theCheckText){this.each(function(){$(this).focus(function(event){if($(this).val()==theCheckText) $(this).val('');}).keydown(function(event){if(event.which==13){theButton.click();event.preventDefault();}});});}
,mdcSwitchImage:function(){this.each(function(){$(this).addClass('mdcImgSwitch').hover(function(){$(this).mdcImgHover();},function(){$(this).mdcImgOut();});});}
,mdcSwitchImage2:function(){this.each(function(){$(this).parent().parent().addClass('mdcImgSwitch').mouseover(function(){$(this).find("img").mdcImgHover();}).mouseout(function(){$(this).find("img").mdcImgOut();});});}
,mdcSwitchBkg:function(){this.each(
	function(){$(this).hover(
		function(){$(this).css("background-image",$(this).css("background-image").replace(/Off/,'Over'));},
		function(){$(this).css("background-image",$(this).css("background-image").replace(/Over/,'Off'));});});}
,mdcAGSalesTable:function(){
	$(this).each(function(){
		$(this).find("tr").hover(function(){$(this).addClass("mdcHover");},function(){$(this).removeClass("mdcHover");});
	});
}
,mdcTableColor:function(theHeaderFlag){
	$(this).each(function(){
		var theTrs = theHeaderFlag?$(this).find("tr:not(:first)"):$(this).find("tr");
		theTrs.mdcColorTable(true);
	});
}
,mdcColorTable:function(theSwitchColor){
	$(this).mdcHoverTable();
}
,mdcColorTables:function(theSwitchColor){
	$(this).each(function(){
		$(this).mdcHoverTable();
	});
}
,mdcHoverTable:function(){
  	this.hover(
		function(){$(this).addClass('mdcRowSelect');},
		function(){$(this).removeClass('mdcRowSelect');});
}
,mdcShowMoreText:function()
    {
    this.next().css('display','inline');
    this.css('display','none');
    this.parents('.mdcShowLessDIV').click(function(event)
        {$(this).mdcShowLessText();});
    } 
,mdcShowMoreText2:function(theEvent){this.next().css('display','inline');this.css('display','none');this.parents('.mdcShowLessDIV').click(function(){$(this).mdcShowLessText();});jQuery.event.fix(theEvent).stopPropagation();}

,mdcShowLessText:function()
    {
    this.find('.mdcShowMoreDescription').css('display','none');
    this.find('.mdcShowMore').css('display','inline');
    this.unbind('click');
    }
,mdcHighlightTerms:function(theHaighlighTerms){
    if(theHaighlighTerms == ''){return;}var aHighlightTermsList= theHaighlighTerms.split('##');this.each(
	function(){
		var aTermsRegExp = ""; 
		for(var aHighlightTerm in aHighlightTermsList) {
            aTermsRegExp=aTermsRegExp+aHighlightTermsList[aHighlightTerm]+"|";
		}
		aTermsRegExp=aTermsRegExp.substring(0,aTermsRegExp.length-1);
        var aHighlightTermRegExp=new RegExp('('+aTermsRegExp+')',"gi");
		$(this).html($(this).html().replace(aHighlightTermRegExp, '<span class="mdcHighlightText">$1</span>'));
	}
);}
,SummaryHover:function (theHover){
	this.hover(
		function(){$(this).toggleClass('mdcSummaryHoverInfo').css('background-image',$(this).css("background-image").replace(/Off/,'Over'));$(theHover).css('display', 'block');},
		function(){$(this).removeClass('mdcSummaryHoverInfo').css('background-image',$(this).css("background-image").replace(/Over/,'Off'));;$(theHover).css('display', 'none');}
	);
}
,CheckMinHeight:function(theRightBlock){if($(this).css('height')<$(theRightBlock).css('height')){$(this).css('min-height',$(theRightBlock).css('height'));}}
,AGSaleDPSwitchTab:function(){
	this.each(function(){
		$(this).click(function(){
			$(this).parent().find('span').each(function(){ $(this).removeClass('mdcAGSelectedItem');$('#'+$(this).attr('associateddiv')).addClass('mdcHide');});
			$(this).toggleClass('mdcAGSelectedItem');
			$('#'+$(this).attr('associateddiv')).removeClass('mdcHide');
		});
		$(this).hover(
		function(){$(this).toggleClass('TabHover')},
		function(){$(this).toggleClass('TabHover');}
		);
	});
}
,AGTabHover:function(theSelectedClassName){
	this.each(function(){
		$(this).click(function(){$(this).removeClass("mdcHover");}).hover(
		function(){
			if(!$(this).hasClass(theSelectedClassName)) {
				$(this).addClass('mdcHover')
			}
		},
		function(){
			if(!$(this).hasClass(theSelectedClassName)) {
				$(this).removeClass('mdcHover');
			}
		}
		);
	});
}
,ShowTableRows:function(theRowNum, theColNum){
	var iRowCount = $(this).find('tr').length;
	var iColCount = theColNum;
	if(iRowCount<theRowNum)
	{
		var sHtml = '';
		for(var i=0;i<theRowNum-iRowCount;i++)
		{
			sHtml=sHtml+'<tr>';
			for(var j=0;j<iColCount;j++)
			{
				sHtml = sHtml+'<td>&nbsp;</td>'
			}	
			sHtml=sHtml+'</tr>';
		}
		if($(this).html())
		{
			$(this).append(sHtml)
		}
	}
},
showUpdateError:function(theMessage){
	$(this).children("div.mdcUpdate")
		.css("background-image","none")
		.find("p.mdcErrorMessage").html(theMessage);
},
cancelUpdatingOn:function(){
	$(this).css("position","").find("div.mdcUpdate").remove();
},
updateOn:function(){
	this.each(function(){
	if($(this).children("div.mdcUpdate").length>0) return;
	$(this).css("position","relative").append(
	$("<div class='mdcUpdate'>" + 
		"<p class='mdcErrorMessage'></p></div>")
		.css("left","0")
		.css("top","0")
		.css("position","absolute")
		.css("z-index","9999")
		.css("width",$(this).width())
		.css("height",$(this).height())
		.css("background","url(/_Layouts/Mdc/Images/AjaxLoading_5.4.2009.511.gif) no-repeat 50% 40px #eeeeee")
		.css("opacity","0.9")
		.css("filter","progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=90,finishOpacity=100)")
		);
	});
},
showTabs:function(){
    $(this).each(function(){
        $(this).hover(
			function(){if($(this).hasClass('mdcTabSelected')||$(this).hasClass('mdcTabGray'))return;$(this).toggleClass('mdcHover');},
			function(){if($(this).hasClass('mdcTabSelected')||$(this).hasClass('mdcTabGray'))return;$(this).toggleClass('mdcHover');}
		);	
		$(this).click(function(){
            if($(this).hasClass('mdcTabGray'))return;
			$(this).siblings().removeClass('mdcTabSelected'); $(this).removeClass('mdcHover');$(this).addClass('mdcTabSelected');
			var sId = $(this).attr('id'); 
			var sDesId=sId.substring(0,sId.length-3);
			$('#'+sDesId).siblings().css('display','none');
			$('#'+sDesId).css('display','block');
		});
    });
}
,DD_FREEMOVE:0 
,DD_HMOVE:1 
,DD_VMOVE:2 
,ObjectDragDrop:function(theActiveArea)
{
    var me = this;
    var clientX = 0;
    var clientY = 0;
    var clientTop = 0;
	var clientLeft = 0;
    this.moveStyle = $(this).DD_FREEMOVE ;
    this.onmousedown = function(theEvent){};
    this.onmouseup = function(theEvent){};
    this.onDrop = function(){};
    this.onDrag = function(theMoveLen){};
    this.isMoved = function(theOffsetX, theOffsetY){return {x:true,y:true}};
    $(this).mousedown(function(e){
          var foo = me;
          e = e||event;
          document.onselectstart = function(){ return false; };
          clientX = e.clientX;       
          clientY = e.clientY;       
          clientTop = parseInt($(foo).position().top);
		  clientLeft = parseInt($(foo).position().left);
		  me.onmousedown(e);
    });    
	theActiveArea.mousemove(function(e){
		var foo = me;
		e=e||event;
		if(clientX == 0 || clientY == 0)
			return;
		var mv = me.isMoved(e.clientX - clientX, e.clientY - clientY);
		if (mv.x&&me.moveStyle!=$(this).DD_VMOVE)
		{
			$(foo).css('left',e.clientX - clientX + clientLeft);
			me.onDrag(e.clientX - clientX);
		}
		if (mv.y&&me.moveStyle!=$(this).DD_HMOVE)
		{
			$(foo).css('top',e.clientY - clientY + clientTop);
			me.onDrag(e.clientY - clientY);
		}
	});    
    theActiveArea.mouseup(function(e){
		if(clientX == 0 || clientY == 0)
			return;
		e=e||event;
		clientX = 0;
		clientY = 0;
 		document.onselectstart = function(){ return true; };
		me.onDrop();   
   });       
    return this;
}
,SP_LEFTRIGHT: 1 
,SP_UPDOWN: 2 
,mdcSplit:function(theLeftOrTopObj, theSPType, theActiveArea)
{
	var me = this;
	var width = 0;
	var height = 0;
	this.dragObj =  (typeof theLeftOrTopObj=="string")?$(theLeftOrTopObj):theLeftOrTopObj;
	this.activeArea =  (typeof theActiveArea=="string")?$(theActiveArea):theActiveArea;
	this.spType = (theSPType==$(this).SP_UPDOWN)?$(this).SP_UPDOWN:$(this).SP_LEFTRIGHT;        
    this.dd = $(this).ObjectDragDrop(this.activeArea);
	this.dd.moveStyle = (this.spType==$(this).SP_LEFTRIGHT)?$(this).DD_HMOVE:$(this).DD_VMOVE;
    this.dd.isMoved = function(theOffsetX,theOffsetY){    
		if (me.spType==$(this).SP_LEFTRIGHT)
		{        
			var mw1 = parseInt($( me.dragObj).css("min-width"));	
			if (!mw1){mw1 = 0;}
			return {x:width+theOffsetX>=mw1,y:false}; 
		}else
		{
			var mh1 = parseInt($(me.dragObj).css("min-height"));
			if (!mh1){mh1 = 0;}
			return {x:false,y:height+theOffsetY>=mh1}; 
		}
	};
	this.dd.onmousedown =function(theEvent)
	{
		width = parseInt($( me.dragObj).width());
		height = parseInt($( me.dragObj).height());
	}
    this.dd.onDrag= function(theMoveLen){     
 		if (me.spType==$(this).SP_LEFTRIGHT)
	    {		       
			 me.dragObj.width(width + theMoveLen); 
		}else
		{		
			  //fixed   ie6  bug
        	 me.dragObj.parent().height('auto');	
        	 me.dragObj.height(height + theMoveLen); 
        	 if(theLeftOrTopObj.height() > theLeftOrTopObj.find('table').height())
        	    theLeftOrTopObj.find('table tr:last td').css('border-bottom','1px solid #d1d1d1');
        	 else
        	    theLeftOrTopObj.css('overflow-y','auto');
		}
	};
    this.dd.onDrop= function(){     
    	$(this).focus();
	};
}
});
