onerror = errorHandler;

function errorHandler( msg, url, line ) {
	url = "http://www.getjar.com/site/logError";
	parameters = "msg="+msg+"&url="+url+"&line="+line;
	AJAX_POST( url, parameters );
}

var browserType;
if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {browserType= "gecko"}

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(strP);
	return document.poppedLayer; 
}

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 containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))      
      break;      
      containee = containee.parentNode;
  }
  while (containee != null);  
  return isParent;
}

function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

//

function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	if ( expires ) expires = expires * 1000;
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function Get_Cookie(name) {
	var cart = document.cookie;
	var index = cart.indexOf(name + "=");
	if (index == -1)
	return null;
	index = cart.indexOf("=", index) + 1;
	var endstr = cart.indexOf(";", index);
	if (endstr == -1) endstr = cart.length;
	return unescape(cart.substring(index, endstr));
}

function newsTab( show ) {
	
	if (show == 1) {
		hideDIV ('preview_tab');
		hideDIV ('preview');		
		showDIV ('edit_tab');
		showDIV ('edit');
		
		obj_butt = getObject ('butt');
		obj_butt.innerHTML = '<input value=" Next >> " name="B1" class="button" type="button" onclick="javascript:newsTab(2);">';
	}
	if (show == 2) {		
		hideDIV ('edit_tab');
		hideDIV ('edit');

		obj_edit = getObject ('edit_text');
		obj_preview = getObject ('preview');
		
		var str = obj_edit.value;		
		var regex = new RegExp(/<(.*?)>/);
		var match = regex.exec( str );					
		if (match == null) str = str.replace( /(\r\n|\r|\n)/g, '<br>' );
		obj_preview.innerHTML = str;
		
		obj_butt = getObject ('butt');
		obj_butt.innerHTML = '<input value=" Submit " name="B1" class="button" type="submit">';		
		
		showDIV ('preview_tab');
		showDIV ('preview');		
	}	
}

function translateTab( show ) {
	
	if (show == 1) {
		hideDIV ('preview_tab');
		hideDIV ('preview');			
		showDIV ('edit_tab');
		showDIV ('edit');		
	}
	if (show == 2) {		
		hideDIV ('edit_tab');
		hideDIV ('edit');

		obj_desc_long = getObject ('desc_long');
		obj_preview_desc_long = getObject ('preview_desc_long');
		obj_preview_desc_long.innerHTML = obj_desc_long.value;				
		
		showDIV ('preview_tab');
		showDIV ('preview');		
	}	
	if (show == 3) {
		hideDIV ('preview_tab2');
		hideDIV ('preview2');			
		showDIV ('edit_tab2');
		showDIV ('edit2');
		
		obj_butt = getObject ('butt');
		obj_butt.innerHTML = '<input value=" Next >> " name="B1" class="button" type="button" onclick="javascript:translateTab(4);">';
	}
	if (show == 4) {		
		hideDIV ('edit_tab2');
		hideDIV ('edit2');

		obj_desc_long = getObject ('desc_long2');
		obj_preview_desc_long = getObject ('preview_desc_long2');
		obj_preview_desc_long.innerHTML = obj_desc_long.value;		
		
		obj_butt = getObject ('butt');
		obj_butt.innerHTML = '<input value=" Save " name="B1" class="button" type="submit">';		
		
		showDIV ('preview_tab2');
		showDIV ('preview2');		
	}	
	
}



function openLinkIfConfirm( link, message ) {
	if( !message || confirm(message) ) 
		window.location.href =link;
}

function openLink( link ) {
	window.location.href = link;
}

function getFileName(url) {
  var index = url.lastIndexOf('\\');  
  if (index != -1) retVal = url.substring(index + 1);
  else retVal = url;
  return retVal;
}

var skipCntAlert = false;
function cnt( w, x, status ){
	if( skipCntAlert )  {
		skipCntAlert = false;
		return;
	}
	var y=w.value;
	var r = 0;
	a=y.replace('\n',' ');
	r = a.length;		
	if (r > x) {				
		skipCntAlert = true;
		if (status == 1) alert('Max. '+x+' chars; no HTML please; appears in WAP and WEB sites');
		if (status == 2) alert('Max. '+x+' chars; HTML allowed; no JavaScript please; appears in WEB site only');
		w.value = y.substring( 0, x );		
	}
}

function AddFile (athis, obj) {
	var FullFileName = getObject(athis).value;	
	var FileName = getFileName(FullFileName);		
	getObject( obj ).innerHTML = '<font size="1">&nbsp;'+FileName+'</font>';
}

function userInputToInteger( value ) {
	var safeValue ="";
	for( var i=0; i<value.length; i++ ) {
		v = parseInt( value[i] );
		if( v >= 0 && v <= 9) safeValue += value[i];
	}

	return safeValue;
}

function AJAX_GET( link ) {
	var http_request = false; 
	if(window.XMLHttpRequest) http_request=new XMLHttpRequest();
	else if (window.ActiveXObject) http_request = new ActiveXObject("Microsoft.XMLHTTP");	
	if( !http_request ) return false; 
	
	window.status = "Please wait...";
	http_request.open('GET', link, false); 
	http_request.send("empty"); 
	window.status = ""; 
	
	if (http_request.readyState == 4 && http_request.status == 200 ) return http_request.responseText; 
	else return false;
}

// PARAMETERS SAME FORMAT AS GET param1=encodeURI(value1)&param2=encodeURI(value2)...
function AJAX_POST( url, parameters ) {
	var http_request = false; 
	if(window.XMLHttpRequest) http_request=new XMLHttpRequest();
	else if (window.ActiveXObject) http_request = new ActiveXObject("Microsoft.XMLHTTP");	
	if( !http_request ) return false;
 
	http_request.open('POST', url, false);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
	
	if (http_request.readyState == 4 && http_request.status == 200 ) return http_request.responseText; 
	else return false;	
}

function popupDiv( divName, title, content, mouseX, mouseY, bgColor ) {
	if ( !bgColor ) bgColor = '#9d8777';
	var s = "<B><A href=\"javascript:hideDIV('"+divName+"');\"><font color=\"black\">[X]</font></a><B> | " + title;
	s = "<table cellpadding=1 cellspacing=1> <tr><Td bgcolor=white><table cellpadding=2 cellspacing=1 bgcolor=\'"+bgColor+"\'><tr><Td style=\'font-size:9px; font-family:verdana;color:white;\'>&nbsp; "+ s + "</TD></tr><tr bgcolor=white><td>";
	s += content;
	s += "<BR></td></tr></table></TD></tr></table>";

	var hintDiv = getObject( divName );
	hintDiv.innerHTML = s;
		
	hintDiv.style.visibility = "visible";
	hintDiv.style.position = "absolute";
	
	hintDiv.style.left = mouseX + 'px';
	hintDiv.style.top  = mouseY + 'px';
}

function popupDiv2( divName, content, mouseX, mouseY ) {
	var hintDiv = getObject( divName );
	hintDiv.innerHTML = content;
		
	hintDiv.style.visibility = "visible";
	//hintDiv.style.position = "absolute";
	hintDiv.style.display = 'block';
	hintDiv.style.left = mouseX + 'px';
	hintDiv.style.top  = mouseY + 'px';
}

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 showHint( hintID ) {
	var host = window.location.hostname;
	var url = 'http://'+host+'/site/?action=ajax_updateHintView&hintID='+hintID;
	var result = AJAX_GET( url );
	var hintDiv = getObject( 'hint_div'+hintID );
	
	hintDiv.style.visibility = "visible";
	hintDiv.style.left = gMouseX - 10 + 'px';
	hintDiv.style.top  = gMouseY - 10 + 'px';
}

function trimString( str ) {
	return str.replace( /^\s+|\s+$/g, '' );
}

// ADD SGS 2008.03.21
function print_r( theObj ){	
	if( theObj.constructor == Array || theObj.constructor == Object ){
    	document.write( "<ul>" );
      	for( var p in theObj ){
      		if( theObj[p].constructor == Array || theObj[p].constructor == Object ){
      			document.write( "<li>["+p+"] => "+typeof( theObj )+"</li>" );
      			document.write( "<ul>");
      			print_r( theObj[p] );
      			document.write( "</ul>");
      		} else {
      			document.write("<li>["+p+"] => "+theObj[p]+"</li>" );
      		}
      	}
      	document.write( "</ul>" );
    }
}

function checkTitles() {
	form = document.getElementById( "edit_form" );
	for( i = 0; i < form.elements.length; i++ ) {
		key = form.elements[i].name.split( "_" );
		if( key[0] != 'name' ) continue;
		if( !AJAX_POST( '/admin_php/do/?action=ajax_isValidSoftName', 'softName='+form.elements[i].value.replace( '+', '%2B' )+'&devID='+key[1] ) ) {
			document.getElementById( 'error_'+key[2] ).innerHTML = "<font color='red'>Incorrect title</font>";
			return false;
		}
		else document.getElementById( 'error_'+key[2] ).innerHTML = '';
	}
	return true;
}

function isDefined( variable ) {
    return (typeof(window[variable]) == "undefined")?  false : true;
}

function addElement( appendSpanDiv, elemName, size, maxLength ) {
	getObject('fields_count').value++;
	var fieldsCount = getObject('fields_count').value;
    
	var div = document.createElement("DIV");
	div.setAttribute("id", 'div_'+elemName+'_'+fieldsCount);
	var elem = document.createElement("input");
	elem.setAttribute("name", elemName+'[]' );
	elem.style.cssText = "font-size: 8pt; font-family: verdana, arial; background-color: #FFFFFF; color: #000000; font-weight: bold; border-style: solid; border-width: 1; border-color: #501B5A";
	elem.setAttribute("id", elemName+"_"+fieldsCount);
	if( size ) elem.setAttribute("size", size);
	if( maxLength ) elem.setAttribute("maxlength", maxLength);
	getObject(appendSpanDiv).appendChild(div);
	getObject('div_'+elemName+'_'+fieldsCount).appendChild(document.createElement("BR"));
	getObject('div_'+elemName+'_'+fieldsCount).appendChild(elem);
	
	removeLink = document.createElement("A");
    removeLink.setAttribute("href", "javascript: removeElement( '"+appendSpanDiv+"', 'div_"+elemName+'_'+fieldsCount+"' )");
    removeLink.innerHTML = "[x]";
    removeLink.style.cssText = "padding-left: 3px;";

    getObject('div_'+elemName+'_'+fieldsCount).appendChild(removeLink);
}

function removeElement( removeChildSpan, elemId ) {
	var fileSpan = getObject(elemId);
	var str = 'Do you want to remove this advertising message?';
	if( !confirm(str) ) return; 
	getObject(removeChildSpan).removeChild(fileSpan);
}

function showHintPopup() {
	html = '<table border="0" width="160" height="66" cellpadding="0" cellspacing="0">';
	html += '<tr>';
		html += '<td>';
			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" style="color:#FFFFFF; font-family:Verdana, Arial; font-size:9px;">User reported compatibility</font></b></td>';
				html += "<td bgcolor=\"#6b6a6a\" align=\"right\"><b><a style=\"color:#FFFFFF; text-decoration:none;\" href=\"javascript:hideDIV('gjHintDiv');\">x<a></b>&nbsp;</td>";
				html += '</tr>';
			html += '</table>';
		html += '</td>';
	html += '</tr>';
	html += '<tr>';
		html += '<td colspan="2" bgcolor="#ffffff" style="font-family:Verdana, Arial; font-size:8px;"><font size="1">Shows your current product compatibility based on users feedback, across all product versions. E.g. if 6 users report the product to be working well and 4 users report the product to fail, the compatibility will be 60%</font></td>';
	html += '</tr>';	
	html += '</table>';		
	
	var hintDiv = getObject( 'gjHintDiv' );
	hintDiv.innerHTML = html;
	hintDiv.style.display = 'block';
	hintDiv.style.left = gMouseX + 7 - hintDiv.offsetWidth + 'px';
	hintDiv.style.top  = gMouseY - 7 + 'px';
	hintDiv.style.visibility = "visible";	
}

function deviceSaveToCookie( manUrlPart, devUrlPart ) {
	//if ( manUrlPart == "universal" && devUrlPart == "all" ) return;
	var prefix = "GJMyDevices_v-1-___";
	var cookieName = "mydevices";
	var maxDevices = 4;
	var dev = new Array();
	
	if ( !( cookieValue = Get_Cookie( cookieName ) ) ) newCookieValue = prefix+manUrlPart+"---"+devUrlPart;
	else {
		cookieValue = cookieValue.substr( prefix.length, cookieValue.length - prefix.length );

		if ( cookieValue.match( manUrlPart+"---"+devUrlPart ) ) {
			if ( cookieValue.match( manUrlPart+"---"+devUrlPart+"___" ) ) cookieValue = cookieValue.replace( manUrlPart+"---"+devUrlPart+"___", "" );
			else cookieValue = cookieValue.replace( manUrlPart+"---"+devUrlPart, "" );
			if ( cookieValue != "" ) newCookieValue = prefix+manUrlPart+"---"+devUrlPart+"___"+cookieValue;
			else newCookieValue = prefix+manUrlPart+"---"+devUrlPart;
		}
		else {
			if ( cookieValue != "" ) newCookieValue = prefix+manUrlPart+"---"+devUrlPart+"___"+cookieValue;
			else newCookieValue = prefix+manUrlPart+"---"+devUrlPart;
		}
	}
	Set_Cookie( cookieName, newCookieValue, "", "/", ".getjar.com" );
}

function getLastSelectedDevice() {
	var prefix = "GJMyDevices_v-1-___";
	if( !(result = Get_Cookie('mydevices')) || window.location.href.indexOf('universal/all') >= 0 ) return 'universal---all';
	result = result.substr( prefix.length, result.length - prefix.length );
	var lastDelimIndex = ( result.indexOf('___') >= 0 ? result.indexOf('___') : result.length );
	return result.substr( 0, lastDelimIndex );
}

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 previewFlash() {
	showDIV("divFlashPreview");
	document.banner1.focus();
	//var obj = getFlashMovieObject('banner1');
	//var playerVersion = swfobject.getFlashPlayerVersion();
	//alert(playerVersion);
	//obj.focus();	
}