//Chrome Drop Down Menu v2.01- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: November 14th 06- added iframe shim technique

var cssdropdown={
disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout
disablemenuclick: true, //when user clicks on a menu item with a drop down menu, disable menu item's link?
enableswipe: 1, //enable swipe effect? 1 for yes, 0 for no
enableiframeshim: 1, //enable "iframe shim" technique to get drop down menus to correctly appear on top of controls such as form objects in IE5.5/IE6? 1 for yes, 0 for no

//No need to edit beyond here////////////////////////
dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,

getposOffset:function(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
},

swipeeffect:function(){
if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){
this.bottomclip+=10+(this.bottomclip/10) //unclip drop down menu visibility gradually
this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)"
}
else
return
this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10)
},

showhide:function(obj, e){
if (this.ie || this.firefox)
this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
if (this.enableswipe==1){
if (typeof this.swipetimer!="undefined")
clearTimeout(this.swipetimer)
obj.clip="rect(0 auto 0 0)" //hide menu via clipping
this.bottomclip=0
this.swipeeffect()
}
obj.visibility="visible"
}
else if (e.type=="click")
obj.visibility="hidden"
},

iecompattest:function(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
},

clearbrowseredge:function(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset
var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
},

dropit:function(obj, e, dropmenuID){
if (this.dropmenuobj!=null) //hide previous menu
this.dropmenuobj.style.visibility="hidden" //hide menu
this.clearhidemenu()
if (this.ie||this.firefox){
obj.onmouseout=function(){cssdropdown.delayhidemenu()}
obj.onclick=function(){return !cssdropdown.disablemenuclick} //disable main menu item link onclick?
this.dropmenuobj=document.getElementById(dropmenuID)
this.dropmenuobj.onmouseover=function(){cssdropdown.clearhidemenu()}
this.dropmenuobj.onmouseout=function(e){cssdropdown.dynamichide(e)}
this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()}
this.showhide(this.dropmenuobj.style, e)
this.dropmenuobj.x=this.getposOffset(obj, "left")
this.dropmenuobj.y=this.getposOffset(obj, "top")
this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
this.positionshim() //call iframe shim function
}
},

positionshim:function(){ //display iframe shim function
if (this.enableiframeshim && typeof this.shimobject!="undefined"){
if (this.dropmenuobj.style.visibility=="visible"){
this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px"
this.shimobject.style.height=this.dropmenuobj.offsetHeight+"px"
this.shimobject.style.left=this.dropmenuobj.style.left
this.shimobject.style.top=this.dropmenuobj.style.top
}
this.shimobject.style.display=(this.dropmenuobj.style.visibility=="visible")? "block" : "none"
}
},

hideshim:function(){
if (this.enableiframeshim && typeof this.shimobject!="undefined")
this.shimobject.style.display='none'
},

contains_firefox:function(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
},

dynamichide:function(e){
var evtobj=window.event? window.event : e
if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
this.delayhidemenu()
else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
this.delayhidemenu()
},

delayhidemenu:function(){
this.delayhide=setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'; cssdropdown.hideshim()",this.disappeardelay) //hide menu
},

clearhidemenu:function(){
if (this.delayhide!="undefined")
clearTimeout(this.delayhide)
},

startchrome:function(){
for (var ids=0; ids<arguments.length; ids++) {
	if (document != null) {
		var c = document.getElementById(arguments[ids]);
		if (c != null) {
			var menuitems=c.getElementsByTagName("a")
			for (var i=0; i<menuitems.length; i++){
				if (menuitems[i].getAttribute("rel")){
					var relvalue=menuitems[i].getAttribute("rel")
					menuitems[i].onmouseover=function(e){
						var event=typeof e!="undefined"? e : window.event;
						cssdropdown.dropit(this,event,this.getAttribute("rel"));
					}
				}
			}
		}
	}
}
if (window.createPopup && !window.XmlHttpRequest){ //if IE5.5 to IE6, create iframe for iframe shim technique
document.write('<IFRAME id="iframeshim"  src="" style="display: none; left: 0; top: 0; z-index: 90; position: absolute; filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)" frameBorder="0" scrolling="no"></IFRAME>')
this.shimobject=document.getElementById("iframeshim") //reference iframe object
}
}

}

// ********************* CONTROLS ***************************

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function loadWidgetBody(user, user_id, author_name, date_string, image, text, uid, is_admin, read_url, edit_url, votes, type) {
    var author = author_name;
    if (user) {
        author = '<a href="/user?id=' + user_id + '">' + user + '</a>';
    }
    var picture = "0";
    if (image) {
        picture = image;
    }
    var admin_link = '';
    if (is_admin == 'True') {
        admin_link = ' <span class="widgetEditLink">| <a href="/' + edit_url + '?id=' + uid + '">Edit</a></span>';
    }
    if (read_url) {
        url = '/' + read_url + '?id=' + uid;
        read_url = '<span class="widgetMore"> <a href="' + url + '">Read More &raquo;</a></span>';
        text = '<a href="' + url + '">' + text + '</a>';
    }
    var vote_html = "";
    if (votes) {
        var form = '<form method="post" action="/submitvote?id=' + uid + '&type=' + type + '"><div class="approvalImages"><input type="image" src="/images/thumbsup.png" name="vote" value="yes"> <input type="image" src="/images/thumbsdown.png" name="vote" value="no"></div></form>';
        vote_html = '<td width="40">' 
                        + '<div class="approvalLarge">'
                            + '<div class="approvalLargeLabel">+' + votes + '</div>'
                            + '<div class="approvalSmallLabel">Votes</div>'
                        + '</div>' + form
                    + '</td>';
    }
    var html = '<div class="widgetBody">'
                    + '<table cellpadding="3" width="100%">'
                        + '<tr valign="top">'
                            + '<td width="66">'
                                + '<div class="widgetPicture">'
                                    + '<img src="/images/' + image + '_small.png" width="64">' 
                                + '</div>' 
                            + '</td>' 
                            + '<td>' 
                                + '<div class="widgetText">' + text + read_url + '</div>' 
                                + '<div class="widgetAuthorInfo">' 
                                    + '- ' + author + ' on <span class="questionDate"> ' + date_string + admin_link                               
                                + '</div>' 
                            + '</td>' 
                            + vote_html
                        + '</tr>' 
                    + '</table>' 
                + '</div>';
    return html;
}

function gotoPage(url) {
    window.location = url;
}

function newWindow(url) {
	var popupWindow = window.open(url + '#bottom', 'Reply', 'height=500, width=800, left=100, top=100, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, directories=no, status=yes');
}

function newWindowTop(url) {
	var popupWindow = window.open(url,'Reply','height=500, width=800, left=100, top=100, resizable=yes, scrollbars=yes, toolbar=no, menubar=no, location=no, directories=no, status=yes');
}

function mergeTextAndCommentCount(text, count) {
    if (count != 'None' && count != '0') {
        text += ' <span class="commentCount">(' + count + ' <img src="/images/comment.gif"/>)</span>';
    }
    return text
}

function hideControl(id) {
    control = document.getElementById(id)
    if (control) {
        control.style.display = 'none'; 
        tab = document.getElementById("header" + id);
        if (tab) {
            tab.className = 'pageTabTitle';
        }
    }
}

function showControl(id) {
    control = document.getElementById(id)
    if (control) {
        control.style.display = '';
        tab = document.getElementById("header" + id);    
        if (tab) {
            tab.className = "pageTabTitleActive";
        }
    }
}

function stringContains(s, t) {
	if (s.indexOf(t) > -1) {
		return true;
	}
	return false;
}

function doSearch() {
	var value = document.getElementById('searchbox').value;
	if (stringContains(window.location.href, "/search")) {
		searchValue(value);
	}
	var g = '/search#' + value;
	window.location = g;
	return false;
}

function tryClear() {
	if (!this.is_cleared) {
		var e = document.getElementById('searchbox');
		e.value = '';
		e.className = 'blacktext';
		this.is_cleared = false;
	}
}

function makeTabActive(tab) {
	var tab = document.getElementById(tab);
	if (tab) {
		tab.className = "page_navigation_active_li";
		tab.innerHTML = tab.innerHTML.replace("inactive", "active").replace("inactive", "active");
	}
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
}

function setCookie(c_name, value)
{
	document.cookie=c_name+ "=" +escape(value);
}

function getReferrer()
{
	var ref = document.referrer;
	if (stringContains(ref, 'careercup.com')) { // If referrer from CareerCup, get cached referrer
		ref = getCookie('ref');
	} else {
		setCookie('ref', ref); // Else, use document.referrer and cache referrer
	}
	return ref;
}

function updateReferrers(url) {
	var links = document.getElementsByTagName('a');
	var iframes = document.getElementsByTagName('iframe');
	var ref = getReferrer();
	var affiliate = 0;
	var amzn_affiliate = "";
	if (stringContains(ref, 'http://www.glassdoor.com') || stringContains(ref, 'http://www.wetfeet.com')) {
		affiliate = 104575;
	} else if (stringContains(ref, 'http://www.softwareinterview.com')) {
		affiliate = 84306;
	} else if (stringContains(ref, 'http://halcyon.usc.edu/~kiran')) {
		affiliate = 104753;
		amzn_affiliate = "careercupkiran-20";
	} else if (stringContains(ref, 'http://technical-interview.com')) {
		affiliate = 130537;
	} else if (stringContains(ref, 'http://www.technical-interview.com')) {
		affiliate = 130537;
	} else if (stringContains(ref, 'http://www.mytechinterviews.com')) {
		affiliate = 139226;
	} else if (stringContains(ref, 'http://mytechinterviews.com')) {
		affiliate = 139226;
	}  else if (stringContains(ref, 'careerbliss.com') || stringContains(ref, 'cybercoders.com')) {
		affiliate = 162685;
		amzn_affiliate = "careercupcb-20";
	}  
	if (affiliate != 0) {
		for (var i = 0; i < links.length; i++) {
			var link = links[i];
			if (stringContains(link.href, 'cl=84190')) {
				link.href = link.href.replace('cl=84190', 'cl=84190&aff=' + affiliate);
			}
		}
	}
	if (amzn_affiliate != "") {
		for (var i = 0; i < links.length; i++) {
			var link = links[i];
			if (stringContains(link.href, 'care01-20')) {
				link.href = link.href.replace('care01-20', amzn_affiliate);
			}		
		}
		for (var i = 0; i < iframes.length; i++) {
			var iframe = iframes[i];
			if (stringContains(iframe.src, 'care01-20')) {
				iframe.src = iframe.src.replace('care01-20', amzn_affiliate);
			}		
		}
	}	
}

function setCookie(name, value, expires) {	
	document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString()); 
}

function setChatDisabled(v) {
	setCookie("disableChat", v);
	if (confirm("Refresh page?")) {
		location.reload(true);
	}
}

function putChat() {
	var val = getCookie("disableChat");
	if (val == "1") {
		document.write('<div style="padding-bottom: 10px; padding-left: 10px; padding-top: 20px; font-size: 10px;"> Chat is disabled. Don\'t you want to hear what people are chatting about? <a onclick="javascript:setChatDisabled(0);" style="cursor:pointer;">Enable Chat</a>.</strong></div>');
	} else {
		document.write('<iframe width="240" height="500" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" allowtransparency="true" src="http://chatterous.com/careercup/embed/?bgcolor=EBF3FF&titlecolor=3171C8&linecolor=98C0FF&type=sidebar&send_button=false"></iframe>\
			<div style="padding-bottom: 10px; padding-left: 10px; padding-top: 20px; font-size: 10px;"> Chat window too small? <a href="http://www.chatterous.com/careercup/" target="_blank">Open in new window. Connect via gchat. Access history.</a> <br/><br/> <strong><a href="/chatroomthings">How to Get Better Chat Responses - READ THIS FIRST</a></strong> | <a onclick="javascript:setChatDisabled(1);" style="cursor:pointer;">Disable Chat</a>.</div>');
	}
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


_activeProductTab = "headerProductBooks";
_activeProductBody = "headerProductBodyBooks";

function switchToProduct(prodTab, prodBody) {
	if (_activeProductTab != null && _activeProductTab != "") {
		var e = document.getElementById(_activeProductTab);
		e.className = 'header_product_tabs';
		_activeProductTab = null;
	}
	if (_activeProductBody != null && _activeProductBody != "") {
		var e = document.getElementById(_activeProductBody);
		e.style.display = 'none';
		_activeProductBody = null;
	}
	
	if (prodTab != null && prodTab != "") {
		var e = document.getElementById(prodTab);
		e.className = 'header_product_tabs_active';
		_activeProductTab = prodTab;
	}
	if (prodBody != null && prodBody != "") {
		var e = document.getElementById(prodBody);
		e.style.display = '';
		_activeProductBody = prodBody;
	}			
}

function postToUrl(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);
    form.submit();
}

function vote(val, commentId, url) {
	var params = {}
	params["val"] = val;
	params["commentId"] = commentId;
	params["redirection"] = document.location.href;
	postToUrl("/vote", params, "post");
}

function writeBookLink(book, indiaStr, body, additional) {
	var india = indiaStr == "True" ? true : false;
	var link = "";
	if (book == "ctci") {
		if (india) {
			link = 'http://www.flipkart.com/books/098478280X&&affid=supportcar';
		} else {
			link = 'http://www.amazon.com/gp/product/098478280X/ref=as_li_ss_tl?ie=UTF8&tag=care01-20&linkCode=as2&camp=217145&creative=399373&creativeASIN=098478280X';
		}
	} else if (book == "tgr") {
		if (india) {
			link = 'http://www.flipkart.com/books/0470927623?affid=supportcar';
		} else {
			link = 'http://www.amazon.com/gp/product/0470927623/ref=as_li_ss_tl?ie=UTF8&tag=care01-20&linkCode=as2&camp=217145&creative=399373&creativeASIN=0470927623';
		}		
	}
	document.write('<a href="' + link + '" ' + additional + ' >' + body + '</a>')
}

function writeBookCode(book, indiaStr) {
	var india = indiaStr == "True" ? true : false;
	if (book == "ctci") {
		if (india) {
			document.write('<iframe src="http://www.flipkart.com/affiliateWidget/simpleBanner?bc=FFFFFF&tc=333333&lc=091670&buy=yes&affid=supportcar&id=ACX3FWPS4C&type=3&price=yes&border=yes&height=260&width=120" style="width:120px;height:260px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>');
		} else {
			document.write('<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&bc1=000000&IS2=1&nou=1&bg1=FFFFFF&fc1=000000&lc1=0000FF&t=care01-20&o=1&p=8&l=as4&m=amazon&f=ifr&ref=ss_til&asins=098478280X" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>')
		}
	} else if (book == "tgr") {
		if (india) {
			document.write('<iframe src="http://www.flipkart.com/affiliateWidget/simpleBanner?bc=FFFFFF&tc=333333&lc=091670&buy=yes&affid=supportcar&id=0XW3F9N15T&type=3&price=yes&border=yes&height=260&width=120" style="width:120px;height:260px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>');
		} else {
			document.write('<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&bc1=000000&IS2=1&nou=1&bg1=FFFFFF&fc1=000000&lc1=0000FF&t=care01-20&o=1&p=8&l=as4&m=amazon&f=ifr&ref=ss_til&asins=0470927623" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>');
		}		
	}
}
