var url = '_connector.php';
var t = new Array();
var flag = true;
var key_ = null;
var sid = null;
var response = "";
var ocontent = null;

function show_(div) {
	$(div).style.visibility="visible";	
}

function concatsid(params) {
	return params + "&v=" +sid;
}

function slideupdown(div, slide) {	
	if($(div)) {
		if(Element.visible(div)) {	
			if(slide == null)
				new Effect.BlindUp(div);
			$(div + 'arrow').innerHTML = "<a href='javascript:void(0);' onclick='slideupdown(\"" + div + "\");'><img src='images/bullet_arrow_down.png' alt='Open' title='Open'></a>";
		}
		else {
			if(slide == null)
				new Effect.BlindDown(div);
			$(div + 'arrow').innerHTML = "<a href='javascript:void(0);' onclick='slideupdown(\"" + div + "\");'><img src='images/bullet_arrow_up.png' alt='Close' title='Close'></a>";
		}
	}
}

function timeout(func, time) {
	setTimeout(func + "()", time);
}

function downloadCount() {
	var p = concatsid("state=kb");	
	timeout("downloadCount", 60000);	
	var tmp = new Ajax.Updater(
		{success:'kbsize'},
		url, 
		{
			method:'get',
			parameters: p,
			onFailure: reportError
			});	
}

function showHelp(tag) {
	new Effect.OpenUp('showHelp');
	var p = concatsid("state=showhelp&tag=" + tag);
		var tmp = new Ajax.Updater(
			{success:'showHelp'},
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError				
			});	

	
}

function removeImage(div,id) {
	var p = concatsid("state=removeimage&id=" + id);
		var tmp = new Ajax.Updater(
			{success:div},
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError				
			});	

	
}
	
function hide1() {
	if($F('username').length == 0 && $F('password').length == 0) {
		new Effect.BlindUp('login');		
	}		
}

function hide_(div) {
	//alert(div);
	$(div).style.visibility="hidden";		
}

function showhide(div) {
	if(Element.visible(div)) {
		hide_(div);
	} else {
		show_(div);
	}	
}
function deleteUnedited() {
	new Effect.Appear('loadrequest');
	var p = concatsid("state=deletetemp0");
		var tmp = new Ajax.Updater(
			{success:'unedited'},
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess:  new Effect.Fade('loadrequest')
			});	
	
}
function request() {
	new Effect.Appear('loadrequest');
	var p = concatsid("state=request&title=" + encodeURIComponent($F('requesttitle')) + "&text=" + encodeURIComponent($F('requesttext')));
		exit();
		var tmp = new Ajax.Updater(
			{success:'requested'},
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess:  new Effect.Fade('loadrequest')
			});	
	
}
function submitBug() {
	new Effect.Appear('loadrequest');
	var p = concatsid("state=bugreport&bugtext=" + encodeURIComponent($F('bugtext')) + "&self=" + encodeURIComponent($F('self')));
		exit();
		var tmp = new Ajax.Request(
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess:  new Effect.Fade('loadrequest')
			});	
	
}

function signup() {
	var p = concatsid("state=signup&name=" + encodeURIComponent($F('name')) + "&email=" + encodeURIComponent($F('email')) + "&password=" + encodeURIComponent($F('password')));
		//alert(p);
	var tmp = new Ajax.Updater(
		{success:'signupstatus'},
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError
				
			});	
	//exit();
		/*onSuccess: function(response) {
					if(response.responseText.indexOf("success")) {
						location.href("index.php?signup=true");
					}*/

}

function notifyClose(id) {
	$('utext').value = "";
	$('posting').show();
	var p=concatsid("state=notifyclose&id="+id);
	var ajax = new Ajax.Request(
		url,
			{
			method: 'get',
			parameters: p,
			onFailure: reportError,
			onSuccess: 	function(response) {
						$('posting').hide();
						$('posts').innerHTML = $('posts').innerHTML + response.responseText;
					}	
		});
}

function checkname() {
		
	var name = encodeURIComponent($F('name'));
	if(name.length > 0) {
		var p = concatsid("state=checkname&name=" + name);	
		var tmp = new Ajax.Updater(
			{success:'namecheck'},
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess:  function(r) {
					r = r.responseText;
					if(r.indexOf("delete.png") != -1) {
						var n = $('name');
						n.select();
						//n.highlight();
					}
										}
			});	
	}
}

function closerequest(id,u) {
	if(confirm("Accepting this driver will close the 'Request' and no more suggestions can be added. Continue?")) {
		var p = concatsid("state=closerequest&id=" + id + "&did=" + encodeURIComponent(u));
		//alert(p);
		var tmp = new Ajax.Updater(
			{success: 'secondaryContent_2columns'}, 
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,	
				onSuccess: new Effect.Appear('secondaryContent_2columns')
			});
	}
}

function suggestDriver(id) {
	var u = prompt("Type in the ID of the driver you think is a good match to the description here:", "");
	if(u.length > 0) {
		var p = concatsid("state=suggestdriver&id=" + id + "&did=" + encodeURIComponent(u));
		//alert(p);
		var tmp = new Ajax.Updater(
			{success: 'secondaryContent_2columns'}, 
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,	
				onSuccess: new Effect.Appear('secondaryContent_2columns')
			});
	}
}

function addcookiejar(id) {
	var u = prompt("Type in the URL you want 64bitdrivers.com to find the CookieJar", "http://");
	//alert("hi");
	//alert(u);
	if(u != null && u.length > 7) {
		//alert("here");
		var p = concatsid("state=cookiejar&id=" + id + "&url=" + u);
		//alert(p);
		var tmp = new Ajax.Updater(
			{success: 'secondaryContent_2columns'}, 
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,	
				onSuccess: new Effect.Appear('secondaryContent_2columns')
			});
	}
}


function updateRecentActivity() {
		//alert("here");
		var tmp = new Ajax.Updater(
			{success:'recentdrivers'},
			url,
				{
				method: 'get',
				parameters: '&state=recentdrivers',
				onFailure: reportError
			});
		setTimeout("updateRecentActivity()", 50000);	
}
function updateRecentPosts() {
		//alert("here");
		var tmp = new Ajax.Updater(
			{success:'recentposts'},
			url,
				{
				method: 'get',
				parameters: '&state=recentposts',
				onFailure: reportError
			});
		setTimeout("updateRecentPosts()", 75000);	
}

function openRequest() {
	new Effect.OpenUp('request');	
}
function openBugForm() {
	new Effect.OpenUp('bug');	
}
function addHelpFile(page) {
	new Effect.OpenUp('helpfile');	
}


function checkResponse(r) {
	response = r.responseText;	
	if(response.length > 0) {
		$('recentdrivers').innerHTML += response;
	}		
}

//updateRecentActivity();


function save() {
	
	Effect.OpenUp('c', 'Saving...');		
		
	//if($F('certified') == null)
		//alert("certifed is null!");
		
	//alert(validated($F('model')));

	var pars = concatsid("state=save"
		+ "&os=" + encodeURIComponent($F('os'))
		+ "&url=" + encodeURIComponent($F('url'))
		+ "&lang=" + encodeURIComponent($F('language'))
		+ "&provider=" + encodeURIComponent($F('provider'))
		+ "&cat=" + encodeURIComponent($('categories').innerHTML)
		+ "&tags=" + encodeURIComponent($F('tags'))
		+ "&title=" + encodeURIComponent(validated($F('title')))
		+ "&model=" + encodeURIComponent(validated($F('model')))
		//+ "&certified=" + $F('certified')
		//+ "&tested=" + $F('tested')
		+ "&id=" + encodeURIComponent($F('id'))
		+ "&version=" + encodeURIComponent($F('version'))
		+ "&rand=" + Math.floor(Math.random()*11));		
		
		//alert(pars);
		//alert(url);		
		go_(pars, 'c', null, 'ok');
		
	pars = concatsid("state=into1&id=" + $F('id'));
		go_(pars, 'secondaryContent_2columns');
		
	 //pars = "state=load"
		/*
		var myAjax = new Ajax.Updater(
			{success: 'status'}, 
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onFailure: reportError,
				onSuccess: 
				//onComplete: Effect.OpenUp('status')
			});*/
	
	
	//$('overlay').hide();
}

function download(id,div) {
	
	var p = concatsid("state=increment&id=" + id + "&sid=" + sid);
	//alert(p);
	var ajax = new Ajax.Updater(
		{success:'downloads'},
		url,
			{method: 'get',
			parameters: p,
			onFailure: reportError
		});

}

function postcomment(id,request) {
	var p=concatsid("state=post&request=" + request + "&id=" + id + "&utext=" + encodeURIComponent($F('utext')) + "&user=" + encodeURIComponent($F('user')) + "&sid=" + sid);
	//alert(p);
	$('utext').value = "";
	$('posting').show();

	var ajax = new Ajax.Request(
		url,
			{
			method: 'get',
			parameters: p,
			onFailure: reportError,
			onSuccess: 	function(response) {
						$('posting').hide();
						$('posts').innerHTML = response.responseText + $('posts').innerHTML;
					}	
		});


}

function reportVirus(id,div) {
	if(confirm("Are you sure you want to report this driver as a 'virus'? Ensure that you have scanned this download before reporting it.")) {
		var p = concatsid("state=report&id=" + id);
		var ajax = new Ajax.Updater(
			{success:div},
			url,
				{method: 'get',
				parameters: p,
				onFailure: reportError,
				onSuccess: new Effect.Appear(div)
			});
	}
}

function open_(div) {	
	new Effect.BlindDown(div);	
}

function close_(div) {
	new	Effect.BlindUp(div);	
}

function select_(text,div) {
	//new Effect.Fade('categories');
	$('categories').hide();
	$('categories').innerHTML = escapeChar(text);
	new Effect.Appear('categories');	
	
	
	//$(div).innerHTML = "<span class='selected'>" + text + "</span>";
}

function exit() {
	$('overlay').hide();
	init();
}

function init() {
	$('save_cancel').hide();
	$('ok').hide();
	$('edit').hide();
	$('signup').hide();
	//$('ok_cancel').hide();
	$('request').hide();
	$('bug').hide();
	$('cancel').hide();	
	$('c').hide();
	$('showHelp').hide();
	//$('showHelp').innerHTML = "";
}

Ajax.Responders.register(
    {
        onCreate: function()
        {
            if($('loading') && Ajax.activeRequestCount>0)
            {
				//new Effect.Fade('complete',{duration: .2, queue: 'end'});
                $('loading').show();
            }
        },
 
        onComplete: function()
        {
            if($('loading') && Ajax.activeRequestCount==0)
            {
                $('loading').hide();
				//new Effect.Appear('complete',{duration: .2, queue: 'end'});
            }
        }
    }
);

function signopen() {
	//$('overlay').show();
	new Effect.OpenUp('overlay');
	$('signup').show();
}

function edit(key) {
	//alert(key);
	key_ = key;
	new	Effect.OpenUp('overlay');	
	go_("state=load&id=" + key, "edit");
}
function editcloseup(key) {
	//alert(key);
	key_ = key;
	new	Effect.OpenUp('overlay');	
	go_("state=load&id=" + key, "edit");
}

function go_(params, element, msg, keys, stat_element) {
				
		if(element == null)
			element = 'status'; 	
			
		params = params + "&v=" + sid;
		//alert(params);	
		
		//alert(element);
		
		//init();
		
		if(stat_element == null)
			stat_element = element;
		
		if(msg != null || keys != null) {
			var myAjax = new Ajax.Updater(
			{success: element}, 
			url, 
			{
				method: 'get', 
				parameters: params, 
				onFailure: reportError,
				onSuccess: Effect.OpenUp(element, msg, keys)
			});
		}
		else {
			
			var myAjax = new Ajax.Updater(
			{success: element}, 
			url, 
			{
				method: 'get', 
				parameters: params, 
				onFailure: reportError
				//onSuccess: Effect.OpenUp(element)
			});			
		}
		//Effect.Appear(element);
		$(element).show();
}

function getSid() {
		//alert("getting sid");
	sid = $F('session');
	//alert(sid);
}

function requestPages(url)
	{
		if(url.length > 0 && url.indexOf('://') == -1) {
			url = "http://" + url;
		}
		//alert(url);
		var pars = concatsid('state=scrape&url=' + encodeURIComponent(url));		
		//alert(pars);
		if(url.length > 0) {			
			
			Effect.OpenUp('c', '<b>Searching through the submitted URL for available downloads.</b> Please be patient, as depending on the size of the page, this could take some time.', 'cancel');
				
			var myAjax = new Ajax.Updater(
				{success: 'scrapes'}, 
				'scrape_pages.php', 
				{
					method: 'get', 
					parameters: pars, 
					onFailure: reportError,
					onSuccess: morethan
				});
		}
		
	}
	
	
function deleteDriver(id) {
	if(confirm("Are you sure you want to delete this driver? Note that this action cannot be undone.")) {	
		var p = concatsid("state=deletedriver&id=" + id);
		var myAjax = new Ajax.Request(
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess: function(response) {
							if($('list' + id)) {
								new Effect.Fade('list' + id)
							}
							else {
								location.href="driver.php?id=" + id + "&deleted=true";
							}
						}
			});	
		
	}
}
function deleteRequest(id) {
	if(confirm("Are you sure you want to delete this request? Note that this action cannot be undone.")) {	

		var p = concatsid("state=deleterequest&id=" + id);
		var myAjax = new Ajax.Request(
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess: function (response){
					//alert(response.responseText);
					new Effect.Fade('request'+ id);
				}
			});	
	}
}

function deletePost(id,request) {
	if(confirm("Are you sure you want to delete this post? Note that this action cannot be undone.")) {	

		var p = concatsid("state=deletepost&request=" + request + "&id=" + id);
		var myAjax = new Ajax.Request(
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onSuccess: function (response){
					//alert(response.responseText);
					new Effect.Fade('post'+ id);
				}
			});	
	}
}

function rescan(id) {
	if(confirm("Are you sure you want to rescan this driver? This will update Last Modified date, Size and HTTP Response without prompting.")) {
		new Effect.Appear('loadrequest');
		var p = concatsid("state=rescan&id=" + id);
		var myAjax = new Ajax.Updater(
			{success: 'secondaryContent_2columns'}, 
			url, 
			{
				method:'get',
				parameters: p,
				onFailure: reportError,
				onComplete: new Effect.Fade('loadrequest')
			
			});		
	}
	
}

function orderBy(num) {
	$('orderby').value=num;
	monitor();
}
	
function lookwrap(str,curr) {
	
	if($('orderby')) {
		var orderby = $F('orderby');
	}
	else var orderby = 1;

	if(curr == null || isNaN(curr))
		curr = 0;
		
	//$('s').value = "Loading...";
	var pars = concatsid("state=search&srch=" + str + "&p=" + curr + "&orderby=" + orderby);
	//alert(pars);
	var myAjax = new Ajax.Updater(
			{success: 'columnA_2columns'}, 
			url, 
			{	
				method: 'get', 
				parameters: pars, 
				onFailure: reportError,
				onSuccess: function(response) {
						$('searchload').hide();
						//$('s').value = str
				}
			});
	
}
	
function morethan(request) {
	//alert(request.responseText);
	if(request.responseText.length > 0) {
		Effect.OpenUp('c', '<b>Finished scanning the submitted URL.</b> If you feel like editing anything, go ahead. If you want to submit the driver, drag it over the relevant category on the top navigation bar.', 'ok');
	}
	else {
		Effect.OpenUp('c', '<b>Finished scanning the submitted URL, however no valid downloads were found. Sorry</b>. If you\'re sure it\'s there, locate the actual download and submit that address instead.', 'ok');
	}
}

function reportError(request) {
	alert(request.responseText);
//	$('status').innerHTML = request.responseText;
}

function update(id, oldstr, newstr) {
	go_("state=update&id=" + id + "&oldstr=" + oldstr + "&newstr=" + newstr);	
}

function validated(string) {
    for (var i=0, output='', valid=".'&! -_,/\\?#~:\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; i<string.length; i++)
       if (valid.indexOf(string.charAt(i)) != -1)
          output += string.charAt(i)
    return output;
} 

function escapeChar(strInput)
{
  // replace <span  style="background-color:yellow;color:red;font-weight:bold;">special</span> <span  style="background-color:yellow;color:red;font-weight:bold;">characters</span> that will error out in xml
  strInput=strInput.replace(/&/g,"&amp;");  //replace & with &amp;
  strInput=strInput.replace(/</g,"&lt;");	//replace < with &lt;
  strInput=strInput.replace(/>/g,"&gt;");	//replace > with &gt;
  strInput=strInput.replace(/"/g,"&quot;");	//replace " with &quot;
  strInput=strInput.replace(/'/g, "&rsquo;");	//replace ' with &apos;
  return strInput.trim();
  //return strInput.URLEncode();
}

//function iterate(node) {
function elementid(id) {
	var tmp = $(id).firstChild;
	return encodeURIComponent(tmp.firstChild.nodeValue);
}

function mist() {
	alert("called");
	document.getElementById("darkBackgroundLayer").style.display = "";
}

function register_drops(div) {
	Droppables.add(div, {
		hoverclass: 'underline',
		onDrop: save_node
	});	
}

function register_observer(div) {
	Draggables.addObserver(div, {
		initialize: function(element) {
            this.element = $(element);
         },
						   
		onStart: function() {
            alert('Let\'s go!');
          },
		onEnd: function() {
			alert("end");	
		}
	});	
}

function load_companies(val) {
	var pars = "state=load_comp"
	+ "&curr=" + val;
	
	go_(pars, 'companies');
	/*var myAjax = new Ajax.Updater(
		{success: 'companies'}, 
		url, 
		{
			method: 'get', 
			parameters: pars, 
			onFailure: reportError//,
			//onSuccess: Effect.OpenUp('left')
			//onComplete: Effect.OpenUp('status')
		});	*/
}

function save_node(element, droppableElement) {
	
	
	//alert(droppableElement.id);
		//hide original element
		//element.hide();
		//Effect.nHighlight('status');	
	
		//alert(element.id);
		
		var i = element.id;
		
		var pars = "state=save"
		+ "&os=" + elementid('os' + i)
		+ "&url=" + $F('url' + i)
		+ "&lang=" + elementid('lang' + i)
		+ "&provider=" + elementid('comp' + i)
		+ "&cat=" + droppableElement.id
		+ "&tags=" + elementid('comments' + i)
		+ "&r=" + Math.floor(Math.random()*11);		
		
		var myAjax = new Ajax.Updater(
			{success: 'status'}, 
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onFailure: reportError,
				onSuccess: Effect.OpenUp('status')
				//onComplete: Effect.OpenUp('status')
			});
		
			
	//Ajax.Request("_connector.php?state=save&os=" + elementid('os' + i) + "&url=" + url + "&lang=" + elementid('lang' + i), saved);
}

Effect.nHighlight = function() {
	
	 //var element = $(element);
	 var element = $('surround');
	 if(Element.visible(element)) {
	     new Effect.Highlight(element, {duration: 0.5, startcolor: '#2a56b0'});
	 }
}

Effect.OpenUp = function(el, message, keys) {	

	 //if(key != null)
	 //	$(key).hide();
	 init();
	 
	 var element = $('overlay');
	 var element_inner = $(el);
	 
	 if(!Element.visible(element)) {
	 	element.show();
		//new Effect.Appear($('surround'));
		$('surround').show();
	 }
     else
	 	new Effect.nHighlight(); 	
	 
	 var top = $('c');
	 if(message != null) {
	 	element_inner.innerHTML = message;
	 }	
	 element_inner.show();	
	// else  
	// 	if(element.innerHTML.length = 0)
	//	 	element.innerHTML = "Please Wait...";
	 //$('edit').hide();	 
	
	  
	 //if(!Element.visible(element)) {
		// new Effect.Appear(top);
	 
	 
	 //}	
	 // alert(keys);
	  
	  if(keys != null) {
	  	$(keys).show();
		key = keys;
	  }
 }
 
 Effect.Expand = function(element) {	
	var e = $(element);
	if(flag) {
		flag = false;
		window.setTimeout('flag = true', 500);
		if(!Element.visible(e)) {
			new Effect.BlindDown(e, {duration:0.5});
		}
		else {
			new Effect.BlindUp(e, {duration:0.5});
		}	
	}
 }
 


 Effect.CloseDown = function(el) {	 
 
 	 t.shift();	
 	 if(t.length == 0) {	 	
		 if(el == null)
			 var element = $('status');
		 else var element = $(el);
		 
		  
		 if(Element.visible(element)) {
			 new Effect.Fade(element);
		 }
	 }
 }

function slideUp() {
	//if(Element.Visible('status')) {
		new Effect.SlideUp('status');
	//}
}

function slideDown() {
	new Effect.SlideDown('status');	
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


function check(e, div, val) {
   	 var key;
	 //alert("here");
	 var v = document.getElementById("edit").value;

	 if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

	//alert(key);

     if(key == 13 || key == 9 || v.length > 40) {
          toggle(div);
		  return;
	 }
}

//getSid();

