var browserType;
if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {browserType= "gecko"}

function getScrollTop() {
	if (document.documentElement && document.documentElement.scrollTop)
		return document.documentElement.scrollTop;
	return document.body.scrollTop;
}

function getScrollLeft() {
	if (document.documentElement && document.documentElement.scrollLeft)
		return document.documentElement.scrollLeft;
	return document.body.scrollLeft;
}

// MOUSE
var gMouseX = 0;
var gMouseY = 0;

var IE = document.all ? true : false;
//if (!IE) document.captureEvents(Event.MOUSEMOVE); // TODO 

document.onmousemove = getMouseXY;
function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    gMouseX = event.clientX + getScrollLeft();
    gMouseY = event.clientY + getScrollTop();
  } else {  // grab the x-y pos.s if browser is NS
    gMouseX = e.pageX;
    gMouseY = e.pageY;
  }  

  return true;
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))      
      break;      
      containee = containee.parentNode;
  }
  while (containee != null);  
  return isParent;
}

function getObject(id_name) {
	var strE = "document.getElementById(\'"+id_name+"\')";
	var strS = "document.all[\'"+id_name+"\']";
	var strP = "document.layers[\'"+id_name+"\']";
	
	if (browserType == "gecko" ) document.poppedLayer = eval(strE);
    else if (browserType == "ie") document.poppedLayer = eval(strS);
    else document.poppedLayer = eval(strE);
	return document.poppedLayer; 
}

function getCookie( name ) {
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end)); 
}

function setCookie( name, value ) {
	var theDate = new Date();
	var oneYearLater = new Date( theDate.getTime() + 31536000000 );
	var path = "/";
	var expires = oneYearLater;
	var domain = "";
	var secure = "";
		
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function hideDIV(id_name) {		
    var pLayer = getObject(id_name);
    if( pLayer == null ) return;
   // if( pLayer.style.visibility == "hidden") return;

    pLayer.style.visibility = "hidden";
    pLayer.style.position = "absolute";    
}

function showDIV(id_name) {		
    var pLayer = getObject(id_name);
    if( pLayer == null ) return;
    if( pLayer.style.visibility == "visible") return;
    
    pLayer.style.visibility = "visible";
    pLayer.style.position = "";    
    pLayer.style.display = "block";
}

function hideSearchBox( e ) {
	var targ;
	if(!e) var e = window.event;
	if(e.target) targ=e.target;
	else if(e.srcElement) targ=e.srcElement;
	
	if(targ.nodeType==3) targ = targ.parentNode; // defeat Safari bug
	var objID = targ.id; 
	var parentID = targ.parentNode.id; 

 	if( parentID == 'searchBox' || parentID == 'searchBoxItemId' || objID == 'keywords' ) return;
  
 	var obj = getObject('searchBox');
 	if( obj != null ) obj.style.visibility = 'hidden';

 	var k = getObject('keywords');
 	if( k != null && k.value == '' && objID != 'searchBtn' ) k.value = 'Search';
 	searchBoxShowing = false;  
}

function popupDiv( divName, title, content, reDraw, onMouseOut, posLeft, posTop, popupWidth ) {
	if( !onMouseOut ) onMouseOut = 'hideDIV(\''+divName+'\');';
	if( !popupWidth ) popupWidth = 180;
	html = '<table border="0" width="'+popupWidth+'" cellpadding="0" cellspacing="0" style="border:1px solid #3F3F3F; font-family:Tahoma,Helvetica,sans-serif; font-size:11px;" onmouseout="javascript:if (checkMouseLeave(this, event)) '+onMouseOut+';">';
	html += '<tr>';
		html += '<td valign="top">';
			html += '<table border="0" width="100%" cellpadding="0" cellspacing="0">';
			html += '<tr>';
				html += '<td width="90%" height="20" bgcolor="#6b6a6a">&nbsp;<b><font size="1" color="#FFFFFF">'+title+'</font></b></td>';
				html += "<td bgcolor='#6b6a6a' align='right'><b><a style='color:#FFFFFF; text-decoration:none;' href='javascript:hideDIV(\""+divName+"\");'>x<a></b>&nbsp;</td>";
				html += '</tr>';
			html += '</table>';
		html += '</td>';
	html += '</tr>';
	html += '<tr>';
		html += '<td colspan="2" bgcolor="#ffffff" style="padding:5px;">'+content+'</td>';
	html += '</tr>';	
	html += '</table>';	

	var hintDiv = getObject( divName );
	hintDiv.innerHTML = html;
	hintDiv.style.position = "absolute";
	hintDiv.style.display = "block";
	
	if( !reDraw ) {
		hintDiv.style.left = (posLeft ? posLeft : gMouseX + 7 - hintDiv.offsetWidth) + 'px';
		hintDiv.style.top  = (posTop ? posTop : gMouseY - 7) + 'px';
	}
	hintDiv.style.visibility = "visible";
}

function showHintPopup( percents, count, device ) {
	var content = percents+" of "+count+" users having "+device+" reported the application working on their phone";
	popupDiv( "gjHintDiv", "User reported compatibility", content );
}

function showCompatabilityInfo() {
	html = 'Device compatibility table based on user reports:<br/><br/>';
	html += '<font color="green">Green</font> - 75% or more users reported device as compatible<br/>';
	html += '<font color="gray">Brown</font> - 25% to 50%<br/>';
	html += '<font color="red">Red</font> - 25% or less';
	popupDiv( 'supported_dev_div', 'Supported Devices', html );
}

function onTabMouseOver( thisElem, color, linkColor ) {
	thisElem.style.backgroundColor = color;
	changeLinkColor( thisElem, linkColor );
}

function onTabMouseOut( thisElem, linkColor ) {
	thisElem.style.backgroundColor = "";
	changeLinkColor( thisElem, linkColor );
}

function openTabLink( tabLink, event ) {
	elem = event.target || event.srcElement;
	if( elem.tagName == 'A' ) return;
	window.location = tabLink;
}

function changeLinkColor( parentElem, linkColor ) {
	for( var i = 0; parentElem.childNodes[i]; i++ ) {
		var parentElemChild = parentElem.childNodes[i];
		if( parentElemChild.tagName == "A" ) parentElemChild.style.color = linkColor;
	}
}

function getTicket() {
	var result = getCookie( "eapiCampaignCheck" );
	return result;
}

function removeAllChildNodes( node ) {
	if( node && node.hasChildNodes && node.removeChild )
		while( node.hasChildNodes() )
			node.removeChild( node.firstChild );
}

function initChannel() {
	var link = "/export/software/?channelID="+channelID+"&type="+type;
	if( category ) link += "&category="+category;
	if( referer ) link += "&ref="+referer;
	if(typeof(adsCount) != 'undefined') link += '&adsCount='+adsCount;
	_openLinkJS( link, true );
}

var gjseHistory = new Array();
var currentLocation = '';
var wasClicked = false;

function _openLinkJS( link, skipClickCheck ) {
	if( !skipClickCheck && wasClicked ) return;
	gjseHistory.push(link);
	currentLocation = link;
	wasClicked = true;
	var jsel = document.createElement("SCRIPT");
	jsel.type = "text/javascript";
	jsel.src = "http://channel.getjar.com"+link;
	getObject("scriptContainer").appendChild(jsel);
}

function goBack() {
	if (!Array.indexOf) {
		Array.prototype.indexOf = function (obj, start) {
	    	for( var i = (start || 0); i < this.length; i++ )
	    		if( this[i] == obj ) return i;
	  	}
	}
	
	var index = gjseHistory.indexOf(currentLocation) ? gjseHistory.indexOf(currentLocation) : 0;
	if( index > 0 ) index = index - 1;
	_openLinkJS(gjseHistory[index]);
}

// CROSS-DOMAIN AJAX

function getHostNameFromURL( url ) {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return url.match(re)[1].toString();
}

function compareDomainName( url ) {
	if( window.location.hostname == getHostNameFromURL( url ) ) return true;
    return false;
}

var ajax_cd_request = {
    ajax_result : '',
    reqMethod : '',
    methodParams : '',
    passAjaxResult : true,

    request_send: function( url, method, params, getRequestResult ) {
    	this.reqMethod = method;
    	this.methodParams = params;
    	this.passAjaxResult = getRequestResult;
    	if( !compareDomainName( url ) ) {
	        request_script = document.createElement("script");
		    request_script.src = "http://channel.getjar.com/php/libs/ajaxCrossDomain.php?url=" + escape(url);
		    document.getElementsByTagName("head")[0].appendChild(request_script);
    	} else ajax_cd_request.request_receive( AJAX_GET(url) );
    },
          
    request_receive: function( data ) {
    	if( !this.reqMethod ) return;
    	this.ajax_result = data;
    	if( this.passAjaxResult ) this.methodParams[this.methodParams.length] = data;
    	this.reqMethod.apply( this, this.methodParams );
    }
}

initChannel();