/**************************************** common.js starts ****************************/
var jQR;
if(jQR) {
	
} else {
	jQR = jQuery.noConflict();
	$ = jQuery.noConflict();
}

var homevar = '';

/* Alert for Inform */
function show_inform(msg_header,msg_txt){	
	try {
	    var orig_msg_txt = msg_txt;
	    var msg_txt = '<p>'+msg_txt+'<\p>';
	    jQR.prompt(msg_header,msg_txt,{
		 buttons:{ Close:1 },
		 prefix:'alert',
		 show:'slideDown',
		 loaded:function(){parent.document.getElementById("alert").focus();}
		
	    },'only_ok','only_ok').children('#colsJqi');
	} catch (e) {
	   alert(orig_msg_txt);
	}
 }
 
 
 /* Alert for Inform with ok trap */
function show_inform_check(msg_header,msg, msgKey){
	try {
		    jQR.prompt(msg_header,msg,{
		     buttons:{ Close:1}, prefix:'alert', show:'slideDown',
		     loaded:function(){parent.document.getElementById("alert").focus();}
		    }, msgKey,'only_ok').children('#colsJqi');
	} catch (e) {
	    msg=msg.replace(/<p>/g,'');
	    msg=msg.replace(/<\/p>/g,'');
	    alert(msg);	    
	    callOKCancelValidatorFunctionNew(1, msgKey);
	}
 } 	

function callOKCancelValidatorFunctionNew(clicked,mid) {
	if(clicked == 1 && mid == "text"){
		
	}
}

 function show_OkCancel(msg_header,msg,msgKey){
		try {
		    jQR.prompt(msg_header,msg,{
			     buttons:{ OK:1 , Cancel:2 }, prefix:'alert', show:'slideDown',
			     loaded:function(){parent.document.getElementById("alert").focus();}
			    }, msgKey,'').children('#colsJqi');
		} catch (e) {
		    msg=msg.replace(/<p>/g,'');
		    msg=msg.replace(/<\/p>/g,'');
		    var conf = confirm(msg);
		    if (conf) {
			callOKCancelValidatorFunctionNew(1, msgKey);
		    }
		}
	}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function splitLongWord(displayName, size) {

	if (displayName == null || displayName.length == 0) {
	    return displayName;
	}
	var newDisplayName = '';
	var wordLen;
	var words = displayName.split(' ');
	for(var i=0; i<words.length; i++) {
		wordLen = words[i].length;
		if(wordLen>size) {
			numFragments = parseInt(wordLen/size) + 1;
			var tmpStr = "";
			for (var k=0;k< numFragments; k++)
			{
				if (k==numFragments-1)
				{
					tmpStr = tmpStr + ' ' + words[i].substr(size*k);
				} else {
					tmpStr = tmpStr + ' ' + words[i].substr(size*k, size);
				}
			}
			newDisplayName = newDisplayName + ' ' + tmpStr.substr(1);
		} else {
			newDisplayName = newDisplayName + ' ' + words[i];
		}
	}
	return newDisplayName.substr(1);
}

function changeShareImage() {
	jQR('.stbuttontext').after('<img alt="More" src="/images/btn-view-more.gif"/>');
	jQR('.stico_default').removeClass('stbutton').removeClass('stico_default');
}

function checkSearch() {
	if(document.getElementById('searchquery').value=='Search') {
		return false;
	} else {
		return true;
	}	
}


function alterShareLinks(){
	jQR('a','.share-box').each(function(){
		var targetobj = jQR('a.targethref',jQR(this).parent().parent().parent().parent().prev());
		var targetUrl = encodeURIComponent(jQR(targetobj).attr('href'));
		var title = 'McGraw-Hill&ate=AT-xa-4bad086714c65333/-/-/4bc7806bd87720dd/10/4bba4b86d70ebdb0&uid=4bba4b86d70ebdb0&CXNID=2000001.5215456080540439074NXC&tt=0'; 
		var newHref = '';
		if(jQR.trim(jQR(this).attr('class')).indexOf('addthis_button_email')>-1) {
			jQR(this).attr('addthis:url', targetUrl);
		} else if(jQR.trim(jQR(this).attr('class')).indexOf('addthis_button_facebook')>-1) {
			newHref = "http://www.facebook.com/sharer.php?u="+targetUrl;
			jQR(this).attr('href', newHref);
			jQR(this).attr('target', '_blank');
		} else if(jQR.trim(jQR(this).attr('class')).indexOf('addthis_button_twitter')>-1) {
			newHref = "http://www.addthis.com/bookmark.php?v=250&winname=addthis&pub=xa-4bad086714c65333&source=men-250&lng=en&s=twitter&url="+targetUrl+"&title="+title;
			jQR(this).attr('href', newHref);
			jQR(this).attr('target', '_blank');
		} else if(jQR.trim(jQR(this).attr('class')).indexOf('yt')>-1) {
			newHref = "http://www.addthis.com/bookmark.php?v=250&winname=addthis&pub=xa-4bad086714c65333&source=men-250&lng=en&s=digg&url="+targetUrl+"&title="+title;
			jQR(this).attr('href', newHref);
			jQR(this).attr('target', '_blank');
		} else if(jQR.trim(jQR(this).attr('class')).indexOf('addthis_button_delicious')>-1) {
			newHref = "http://www.addthis.com/bookmark.php?v=250&winname=addthis&pub=xa-4bad086714c65333&source=men-250&lng=en&s=delicious&url="+targetUrl+"&title="+title;
			jQR(this).attr('href', newHref);
			jQR(this).attr('target', '_blank');
		}
	});
	
	initAddThis();

}

function manageGenericImageHW() {
	jQR(".img-adjust").each(function(){
		try{
			var wid = this.width;
		} catch(e) {
			alert(e);
		}	
		var isAnchor =  jQR(this).parent().is("a");
		var profile =  jQR(this).parent().parent().attr("class");

		if(isAnchor){
			jQR(this).parent().parent().next().css('width', wid);
			jQR(this).parent().parent().css('width', wid);
			jQR(this).parent().parent().parent().css('width', wid);
		}else if(profile == "profile"){
			jQR(this).parent().css('width', wid);
		}
		else{
			if(jQR.browser.msie){
				//jQR(this).parent().css('padding-left','3px');
				jQR(this).parent().parent().css('padding','6px 3px');
			}
			jQR(this).parent().next().css('width', wid);
			jQR(this).parent().css('width', wid);
			jQR(this).parent().parent().css('width', wid);
		}
	});
}

function prepareVideo() {
	
	jQR('a', '.video').click(function(){
		
		jQR("div.video-holder", ".popup-frame").each( function () {
	        var linkID = jQR('a', this).attr('id');
	        $f(linkID, {src: "/media/flowplayer.commercial-3.1.5.swf", wmode: "transparent"}, {					
				key:'#@9e6727abcdeb9f966ef', 
					clip: {
						autoPlay: false, 
						autoBuffering: true
					}
				}
			);		
		});
		
	});
	
}

function includeHomeTicker() {
	jQR("#share-col1").find('div.ticker').remove();
	jQR("#share-col1").find('h2').after('<div class="ticker"><img id="ticker" src="'+tickerimg+'" /></div>');
	window.setTimeout("includeHomeTicker()", parseInt(refreshtime));
}

function loadTumblr () {
  $.jGFeed('http://mcgrawhillcompanies.tumblr.com/rss',
  function(feeds){
  if(!feeds){
    return false;
  }
  var html = '<div class="items">';
  for(var i=0; i<feeds.entries.length; i++){
    var entry = feeds.entries[i];
    html += '<div class="item">';
    html += '  <div class="content">';
    html += '    <a href="'+entry.link+'">'+entry.title+'</a>';
    html += '    <p>'+entry.publishedDate+'</p>';
    html += '  </div>';
    html += '</div>';
  }
  html += '</div>';
  document.getElementById('tumblr-widget').innerHTML = html;
  }, 6);
}

function prepareLeftMenu() {
	jQR('li', '#nav').hover(function(){
		jQR('.drop', '#nav').css('top', '-9999px').css('left', '0');
		jQR(this).css('position', 'relative');
		if(homevar == 'home') {
			jQR('.drop', this).css('top', '0px').css('left', '211px');
		} else {
			jQR('.drop', this).css('top', '-2px').css('left', '160px');
		}		
	}, function(){
		jQR(this).css('position', 'static');
		jQR('.drop', this).css('top', '-9999px').css('left', '0');
	});
}
function resize(){
	try{
		var iframes = document.getElementsByTagName("iframe");			
		iframes[0].style.height = iframes[0].contentWindow.document.body.scrollHeight + "px";
		iframes[0].style.width = iframes[0].contentWindow.document.body.scrollWidth + "px";	
	} catch (e){}
}
function loadPrivacy(source){
	try{
		if(langStack){
			langStack.push(document.getElementById('iframeId').src);
		}
		var iframes = document.getElementsByTagName("iframe");	
		var iframeDiv = document.getElementById("privacyLangId");
		iframeDiv.innerHTML  = '';
		var tempIframeHTML = '<iframe id="iframeId" name="iframeName" scrolling="no" frameborder="0" src="'+source+'"></iframe>';
		iframeDiv.innerHTML = tempIframeHTML;
		window.setTimeout("resize()",2000);	
	} catch (e){}
}

function checkJobSearchAction() {
    var key = document.getElementById('keywordtmp').value;
    var jobID = document.getElementById('jobNumberSearchtmp').value;
    if(key != 'Keywords...') {
        document.getElementById('keyword').value = key;
    }
    if(jobID != 'Job #') {
        document.getElementById('jobNumberSearch').value = jobID;
    }			
	document.getElementById('jobfield1').value = document.getElementById('jobfield').value;
	//document.getElementById('location1').value = document.getElementById('location').value;
	var value = document.getElementById('location').value;
	if(value == '-1') {
		alert('Please select a region to proceed');
		return;
	}
	document.getElementById('organization1').value = document.getElementById('organization').value;
	var action = document.ftlform.action;
	action = action.replace('$param',value);
	document.ftlform.action = action;
	document.ftlform.submit();
}

function fetchVideo() {
	var fName = document.getElementById('fileName').value;
	if(fName != ''){
		document.getElementById('video-content').innerHTML = '<img src="/images/animation.gif" style=""/><br/>Fetching Video...';
		var url = '/ajax/fetchVideo.do?fileName='+fName;
		AjaxUtil.request(url, {
			onComplete: function(xmlHttpReq) {
				var message =  xmlHttpReq.responseText;
				try {
					document.getElementById('video-content').innerHTML="";		
					document.getElementById('video-content').innerHTML = message;
					
					jQR("div.video-holder",'#video-content').each( function () {
						jQR("#pl").scrollable({items:'div.entries', size:1, clickable:false});
						var link = jQR(this).find("a");
						if(jQR.browser.msie){
							jQR("img",link).attr('src','/images/play.gif');
						}
						var flv_file = link.attr("href");
						$f("player", 
								"/media/flowplayer.commercial-3.1.5.swf", {
									key:'#@9e6727abcdeb9f966ef', 
									clip: {
										autoPlay: false, 
										autoBuffering: true
									}
								}
						).playlist("div.entries");
					 });

					bindHoverVideo();						

				} catch(e){}
			}
		});
	}
	 
}

function bindHoverVideo(){
	jQR("a.prevPage",".aside").hover(
		function(){
			jQR(this).addClass('prevPageHover');
		},function(){
			jQR(this).removeClass('prevPageHover');
		}	
	);
	jQR("a.nextPage",".aside").hover(
		function(){
			jQR(this).addClass('nextPageHover');
		},function(){
			jQR(this).removeClass('nextPageHover');
		}	
	);
	jQR("a",".entries").hover(
		function(){
			if(jQR.browser.msie){
				jQR(this).addClass('playlistHoverIE');
			}else{
				jQR(this).addClass('playlistHover');
			}
		},function(){
			if(jQR.browser.msie){
				jQR(this).removeClass('playlistHoverIE');
			}else{
				jQR(this).removeClass('playlistHover');
			}
		}	
	);
	
	jQR('a','.entries').click(function(){
		var title = jQR(this).text();
		jQR('h2', '.video-player').text(title);
		jQR('.content', '.video-player').find('p').text(title);
	});
	
}

function reloadHistory(){
	if(langStack != null && langStack.length > 0){
		var source = langStack.pop();
		if(source){
			var iframes = document.getElementsByTagName("iframe");	
			var iframeDiv = document.getElementById("privacyLangId");
			iframeDiv.innerHTML  = '';
			var tempIframeHTML = '<iframe id="iframeId" name="iframeName" scrolling="no" frameborder="0" src="'+source+'"></iframe>';
			iframeDiv.innerHTML = tempIframeHTML;
			window.setTimeout("resize()",2000);	
		}
	}else{
		history.go(-1);
	}
	
}

/* original input-hide.js */

function initInputs()
{
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++ )
	{
		if(inputs[i].type == "text" || inputs[i].type == "password")
		{
			inputs[i].valueHtml = inputs[i].value;
			inputs[i].onfocus = function ()
			{
				if(this.valueHtml == this.value)
					this.value = "";
			}
			inputs[i].onblur = function ()
			{
				this.value != ""? this.value = this.value: this.value = this.valueHtml;
			}
		}
	}
}
function initTextareas()
{
	textareas = document.getElementsByTagName("textarea");
	if (textareas)
	{
		for (var i = 0, length = textareas.length; i < length; i++)
		{
			if (textareas[i].title != "")
			{
				textareas[i].value = textareas[i].title;
				textareas[i].onfocus = function()
				{
					if (this.value == this.title) this.value = "";
				}
				textareas[i].onblur = function()
				{
					if (this.value == "") this.value = this.title;
				}
			}
		}
	}
}


if (window.addEventListener)
{
	window.addEventListener("load", initInputs, false);
	window.addEventListener("load", initTextareas, false);
}
else if (window.attachEvent)
{
	window.attachEvent("onload", initInputs);
	window.attachEvent("onload", initTextareas);
}


/* original main.js  */
var litext = '';
function initTabs(){
	jQR('ul.tabset').each(function(){
		var btn_h = jQR(this);
		var _li = jQR(this).find('li');
		var _btn = jQR(this).find('a');
		var _a = _li.index(_li.filter('.active:eq(0)'));
		if(_a == -1) _a = 0;
		_li.removeClass('active').eq(_a).addClass('active');
		_btn.each(function(_i){
			this._box = this.href.substr(this.href.indexOf("#") + 1);
			if(this._box){
				this._box = jQR('#'+this._box);
				if(_i == _a) this._box.show();
				else this._box.hide();
			}
			this.onmouseover = function(){
				changeTab(_i);
				return false;
			}
			this.onclick = function(){
				changeTab(_i);
				return false;
			}
		});
		function changeTab(_ind){
			if(_ind != _a){
				if(_btn.get(_a)._box) _btn.get(_a)._box.hide();
				if(_btn.get(_ind)._box) _btn.get(_ind)._box.show();
				_btn.eq(_a).parent('li').removeClass('active');
				_btn.eq(_ind).parent('li').addClass('active');
				_a = _ind;
			}
		}
	});
}
function initLightbox(){
	jQR('div.video').each(function(){
		if(jQR(this).find('a').attr('target') == '_blank'){
		}else{
			jQR(this).find('a').fancybox({
				'titleShow'     : false,
				'transitionOut'	: 'elastic'
			});
		}
	});
	
	jQR('div.popup').each(function(){
		var _closer = jQR(this).find('strong.close > a');
		_closer.click(jQR.fancybox.close);
		_closer.click(function(){
			jQR("#at15s").hide();
			return false;
		});
	});
}





jQR(document).ready(function(){
	initTabs();
	initTooltip();
	initLightbox();
	initFakeShare();

	
	var _box1 = jQR('#twocolumns aside.aside').eq(0);
	var _box2 = jQR('#twocolumns div.block').eq(0);
	if (_box1.length && _box2.length) {
		_box1.css('marginTop', -_box2.outerHeight());
	}
	
	// fields
	jQR('div.fields').each(function(){
		var _area1 = jQR('div.col1', this).not('div.add').find('ul'),
		_area2 = jQR('div.add ul', this),
		_remove = jQR('a.btn-remove', this),
		_add = jQR('a.btn-add', this);
		
		_area2.empty();
		
		_area1.find('li').click(function(){
			jQR(this).toggleClass('active');
		});
		_area2.find('li').live('click', function(){
			jQR(this).toggleClass('active');
		});
		
		_add.click(function(){
			_area1.find('li.active').each(function(){
				jQR(this).hide().find('input').val('true');
				var _newLi = jQR('<li>'+jQR(this).text()+' </li>');
				_area2.append(_newLi);
			}).removeClass('active');
			_area1.find('li').removeClass('active');
			_area2.find('li').removeClass('active');
			return false;
		});
		_remove.click(function(){
			_area2.find('li.active').each(function(){
				var _txt = jQR(this).text();
				litext = jQR.trim(_txt);
				jQR(this).remove();
				/*var _liShow = _area1.find('li:contains("'+_txt+'")');
				if (_liShow.text() == _txt)
					_liShow.show().find('input').val('false');*/
				_area1.find('li').each(function(){
					var text = jQR(this).html();
					if (text.match(litext)) {
						jQR(this).show().find('input').val('false');
					}
				});
			});
			_area1.find('li').removeClass('active');
			_area2.find('li').removeClass('active');
			return false;
		});
	});
	try {
		fetchVideo();
	} catch (e) {}	
	try {
		fetchNews();
	} catch (e) {}	
	try {
		window.setTimeout("alterShareLinks()",100);
	} catch (e) {}	
	try {
		prepareSearchResultsPagination();
	} catch (e) {}
	try {
		fetchCollectionCount();
	} catch (e) {}
	try {
		prepareVideo();
	} catch (e) {}	
	try {
		changeShareImage();
	} catch (e) {}	
	try {
		prepareLeftMenu();
	} catch (e) {}	
	try {
		includeHomeTicker();
	} catch (e) {}
	try{
		window.setTimeout("resize()",1000);
	} catch (e) {}
	try {
		if (prizePage == true) {
		      jQR("#esId").hide();
		} 
		makeCarousal();
	} catch (e)	{}
  try {
    loadTumblr();
  } catch (e) {
  }
	
});

jQR(window).load(function() {
	try {
		manageGenericImageHW();
	} catch (e) {}
  try {
    $('#slider').nivoSlider();  
  } catch (e) {}  
});

function initAddThis() {
  if(homevar == 'home') {
     addthis.init()
  }
}

function initFakeShare(){
	jQR('a.fake-share').click(function(){
		var _box = jQR(this).parents('div.box').find('div.share-box')
		_box.fadeIn();
		var _closer = _box.find('strong.close').find('a');
		_closer.click(function(){
			_box.fadeOut();
			return false;
		});
		return false;
	});
}
function initTooltip(){
	jQR('div.video').find('a').each(function(){
		var _item = jQR(this).attr('rel');
		if(_item){
			jQR(this).easyTooltip({
				useElement: _item				   
			});
		}
	});
}

/* original ie-png.js */
var transparentImage = "images/transparent.gif";

function fixTrans()
{
	if (typeof document.body.style.maxHeight == 'undefined') {

	var imgs = document.getElementsByTagName("img");
	
	for (i = 0; i < imgs.length; i++)
	{	
		if (imgs[i].src.indexOf(transparentImage) != -1)
		{
			return;
		}

		if (imgs[i].src.indexOf(".png") != -1)
			{
				var src = imgs[i].src;
				imgs[i].src = transparentImage;
				imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
			}
		}	
	}
	
}

if (document.all && !window.opera)
	attachEvent("onload", fixTrans);

function showHideDesc(id) {
	//var scrollElements = $('newsDataExpanded');
	//new ScrollArea(0, scrollElements);
	if($('#desc-'+id).css('display') == 'none'){ 
		$('#desc-'+id).show('slow'); 
		$('#desc-open-'+id).hide('slow');
		$('#desc-close-'+id).show('slow');
	} else { 
		$('#desc-'+id).hide('slow'); 
		$('#desc-close-'+id).hide('slow');
		$('#desc-open-'+id).show('slow');
	}
}
