function addToFavorites(urlAddress, pageName ) { 
if (window.external) { 
window.external.AddFavorite(urlAddress,pageName) 
} else { 
alert("Sorry! Your browser doesn't support this function."); 
} 
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function YouSure () {
	var d = document.getElementById( 'Really' );
	var to= confirm("Are you sure you want to unsubscribe?");
	if (to == true) {
		d.value = "true";		
		document.getElementById( 'unsubscribe' ).submit();
	}
}		

function showGoesOn( ohID ) {
	$( ohID ).show();
}

function ShowIsOver( ohID ) {
	$( ohID ).hide();
} 

function submitenter(myfield,e)
{
	var keycode;
	
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();

	if (window.event) 
		keycode = window.event.keyCode;
	else if (e) 
		keycode = e.which;
	else 
		return true;
		
	if (keycode == 13)
	{
		if (checkData()) 
			ajaxGetBlogUpdates($('name').value, $('email').value);
		return false;
	} else
		return true;
}        

function ajaxGetBlogUpdates( namep, emailp, ajaxerror, ajaxstatus, ajaxprogress, tohide ) {
	$(ajaxerror).hide();
	$(ajaxstatus).hide();
	$(ajaxprogress).show();
	var name = $(namep).value;
	var email = $(emailp).value;
	new Ajax.Request( '/newajax/getblogupdates', {
		method: 'post',
		parameters: 'name='+name+'&email='+email,
		contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		requestHeaders: new Array( 'Cookie', document.cookie ),
		onSuccess: function( transport ) {
	
			var ret = transport.responseText;
			ret = ret.replace(/^\s+|\s+$/g,"");

			if (ret == "success") {
			
				if (email.toLowerCase().indexOf("@hotmail.com") == -1) {
				
				var success_msg = "Please check your inbox for the confirmation email.\n<br />" +
									"You will not receive any updates via email until you click the confirmation link.";
				
				} else {
				var success_msg = "You are now subscribed to pYzam blog updates!<br />Please check your inbox for the confirmation email.\n<br />" +
				"You will not receive any updates via email until you click the confirmation link. <br><br>" +
				" Please check your junk folder, hotmail sometimes marks our mail as spam!";
				}
				
				$(ajaxprogress).hide();
				$(ajaxstatus).update( success_msg ); 
				$(ajaxstatus).show();

			} else {
				$(ajaxprogress).hide();
				$(ajaxerror).update( ret ); 
				$(ajaxerror).show();
			}
		}
	});
}

function checkData (name, email ) {
	var d = document.getElementById(name);
	var h = document.getElementById(email);
	if (d.value != "") {
		if (h.value != "") {
			if (h.value.indexOf("@") != -1 && h.value.indexOf("@") != 0 && h.value.indexOf(".") != -1 && h.value.indexOf("@") != h.value.indexOf(".")-1) {
				//f.submit();
				return true;
			}else{
				alert('Please enter a VALID email address!');
			}
		}else{
			alert('Please enter an email address!');
		}
	}else{
		alert('Please enter a name!');
	}
	
	return false;
	
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function addEvent(obj, evType, fn){
 if (obj.addEventListener){
   obj.addEventListener(evType, fn, false);
   return true;
 } else if (obj.attachEvent){
   var r = obj.attachEvent("on"+evType, fn);
   return r;
 } else {
   return false;
 }
}

Array.find = function(ary, element){
    for(var i=0; i<ary.length; i++){
        if(ary[i] == element){
            return i;
        }
    }
    return -1;
}


function getElem( elem_name ) {
	return document.getElementById( elem_name );
}

function pc2( p_id ) {
        var args = 'id='+p_id;
        jaxCall( 'pc', 'pc', args, null, null, false );
		return true;
}

function FCx(x){
  var min=15;
  if(x && x.indexOf('get.media')>0){
    x=unescape(x.substring(x.indexOf('&url=')+5,x.length));
  }else{
    if(document.cookie.indexOf('CxIC=1')<=0){
      x='http://media.fastclick.net/w/get.media?sid=32991&m=5&tp=6&url='+escape(x);
      var date_ob=new Date();
      date_ob.setTime(date_ob.getTime()+min*1000*60);
      document.cookie='FCxIC=1; path=/; expires='+date_ob.toGMTString();
    }
  }
  return x
}

function pc( p_id ) {
	//this.href = FCx(this.href);
	var args = 'id='+p_id;

	if (p_id != 2082) {	
		var pyzu='http://x.azjmp.com/1TrZY';var pyzw=950;var pyzh=750;
		var pyzf='width='+pyzw+',height='+pyzh+',toolbar=0,location=0,titlebar=1,menubar=0,scrollbars=0,resizable=0,directories=0,status=0';
		window.open(pyzu,'',pyzf+',left='+((screen.width-pyzw)/2)+',top='+((screen.height-pyzh)/2)).blur();window.focus();
	}

	ajaxCall( 'pc', 'pc', args, null, null, false );
	return true;
}

function rollToy (id, state) {
    var element = document.getElementById(id);
	if (state == 'over') {
	  element.setAttribute("className", "singletoyhover"); 
	  element.setAttribute("class", "singletoyhover");
//	  element.style.backgroundImage='url(/images/v2/toyThumbs/'+id+'-2.jpg)';
	}else{
	  element.setAttribute("className", "singletoy");
	  element.setAttribute("class", "singletoy");
//	  element.style.backgroundImage='url(/images/v2/toyThumbs/'+id+'-1.jpg)';
	}
}
function show_stats (id) {
	if (getElem('stats_for_'+id) && getElem('stats_for_'+id).style)
		getElem('stats_for_'+id).style.visibility = 'visible';

	if (getElem('fs_for_'+id) && getElem('fs_for_'+id).style)
		getElem('fs_for_'+id).style.visibility = 'visible';
}
function hide_stats (id) {
	if (getElem('stats_for_'+id) && getElem('stats_for_'+id).style)
		getElem('stats_for_'+id).style.visibility = 'hidden';

	if (getElem('fs_for_'+id) && getElem('fs_for_'+id).style)
		getElem('fs_for_'+id).style.visibility = 'hidden';
}

function mooLogin(a_form) {
	a_form = $(a_form);
	new Request({
		url:'/newajax/login',
		onSuccess: function(result) {
			var res = result.split(':');
			if (res[0] == '-') {
				if (res[1] == 'blank') {
					window.location.href='/my';
					return;
				}
				$$('.su_message').set('html', res[1]);
			} else {
				if (typeof(loginSuccess) == 'function') {
					loginSuccess();
					return false;
				}

				$$('.su_message').set('html', 'login successful');
				if (res[1] == 'http') {
					window.location.href=res[1]+':'+res[2];
				} else {
					window.location.reload();
				}
			}
		}
	}).send('py_pw='+a_form.py_pw.value+'&py_ea='+a_form.py_ea.value);
}

function betterLogin(a_form) {
	if (typeof(Ajax) != 'object') { // if mootools is loaded instead of prototype
		mooLogin(a_form);
		return false;
	}
	$(a_form);

	a_form.down('.su_message').innerHTML = '...';
	new Ajax.Request('/newajax/login', {
		parameters: a_form.serialize(),
		onSuccess: function(t) {
			var res = t.responseText.split(':');
			if (res[0] == '-') {
				if (res[1] == 'blank') {
					this.window.location.href='/my';
					return;
				}
				a_form.down('.su_message').innerHTML = res[1];
			} else {
				if (typeof(loginSuccess) == 'function') {
					loginSuccess();
					return false;
				}

				a_form.down('.su_message').innerHTML = 'login successful';
				if (window.location.pathname == '/') {
					window.location.href = '/my';
					return;
				}

				if (res[1] == 'http') {
					this.window.location.href=res[1]+':'+res[2];
				} else {
					this.window.location.href=this.window.location.href;
				}
			}
		},
		onFailure: function() {
		   a_form.down('.su_message').innerHTML = 'failure during login';
		}
	});
}
function getXMLHTTPObj()
{
        var xmlhttp=false;
        /*@cc_on @*/
        /*@if (@_jscript_version >= 5)
        // JScript gives us Conditional compilation, we can cope with old IE versions.
        // and security blocked creation of the objects.
         try {
          xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
          try {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (E) {
           xmlhttp = false;
          }
         }
        @end @*/
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                try {
                        xmlhttp = new XMLHttpRequest();
                } catch (e) {
                        xmlhttp=false;
                }
        }
        if (!xmlhttp && window.createRequest) {
                try {
                        xmlhttp = window.createRequest();
                } catch (e) {
                        xmlhttp=false;
                }
        }
        return xmlhttp;
}

function newAjaxCall( remoteObj, remoteAction, args, successFunc, failFunc, localArgs ) {
    var params = "o="+remoteObj+"&"+args
    var action = "/newajax/"+remoteAction;
    
    ajaxPOST( action, params, successFunc, failFunc, localArgs );
}

function ajaxCall( remoteObj, remoteAction, args, successFunc, failFunc, localArgs ) {
    var params = "o="+remoteObj+"&a="+remoteAction+"&"+args
    var action = "/ajax";
    
    ajaxPOST( action, params, successFunc, failFunc, localArgs );
}

function jaxCall( remoteObj, remoteAction, args, successFunc, failFunc, localArgs ) {
    var params = "o="+remoteObj+"&a="+remoteAction+"&"+args
    var action = "/ajax";
    
    return jaxPOST( action, params, successFunc, failFunc, localArgs );
}

function ajaxPOST( action, params, successHandler, failHandler, localArgs ) {
    xmlhttp = getXMLHTTPObj();
    async = true;
    xmlhttp.open("POST", action, async);
    
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttp.setRequestHeader('Cookie', document.cookie);

    var statechangefunc = function( ) {
        if (xmlhttp.readyState==4) {
            text = xmlhttp.responseText.replace(/^\s*|\s*$/g,""); // strip whitespace
			successInd = text.charAt(0);
            if (successInd == '+') {
                if (typeof( successHandler ) == 'function') {
                    //successHandler( {xml: xmlhttp.responseXML, text: text, largs: localArgs} );
                    successHandler( text.slice(2), localArgs ); // drop the first 2 (+:) characters and move on.
                }
            } else if (successInd == '-') {
                if (typeof( failHandler ) == 'function') {
                    //failHandler( {xml: xmlhttp.responseXML, text: text, largs: localArgs} );
                    failHandler( text.slice(2), localArgs ); // drop the first 2 characters (-:) and move on.
                }
            } else {
                alert('Exception occured during request.\n' + text);
            }
        }
    }

    xmlhttp.onreadystatechange=statechangefunc;    
    xmlhttp.send(params);
}

function jaxPOST( action, params, successHandler, failHandler, localArgs ) {
    xmlhttp = getXMLHTTPObj();
    async = false;
    xmlhttp.open("POST", action, async);
    
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttp.setRequestHeader('Cookie', document.cookie);

    var statechangefunc = function( ) {
        if (xmlhttp.readyState==4) {
            text = xmlhttp.responseText.replace(/^\s*|\s*$/g,""); // strip whitespace
			successInd = text.charAt(0);
            if (successInd == '+') {
                if (typeof( successHandler ) == 'function') {
                    //successHandler( {xml: xmlhttp.responseXML, text: text, largs: localArgs} );
                    successHandler( text.slice(2), localArgs ); // drop the first 2 (+:) characters and move on.
                }
            } else if (successInd == '-') {
                if (typeof( failHandler ) == 'function') {
                    //failHandler( {xml: xmlhttp.responseXML, text: text, largs: localArgs} );
                    failHandler( text.slice(2), localArgs ); // drop the first 2 characters (-:) and move on.
                }
            } else {
     //           alert('Exception occured during request.\n' + text);
            }
        }
    }

    xmlhttp.onreadystatechange=statechangefunc;    
    xmlhttp.send(params);
	return true;
}


var g_a = new Array('x','y','z'); // dummy values shouldn't affect anything

document.grabbed_items = g_a;


function ajaxGrab( table, content_id ) {
        var arr = document.grabbed_items;
        // if hte user hasn't already grabbed it
        if (Array.find(arr,content_id+'_grabbed') == -1) {
                var args = 'id='+content_id;

                ajaxCall( table, 'grab', args, null, null, false );

                // don't let people send multiple grab records (at least prevent most of them);
                document.grabbed_items[document.grabbed_items.length] = content_id + "_grabbed";
        }
}

function newAjaxGrab( table, content_id, success ) {
        var arr = document.grabbed_items;
        // if hte user hasn't already grabbed it
        if (Array.find(arr,content_id+'_grabbed') == -1) {
                var args = 'id='+content_id;

                newAjaxCall( table, 'newgrab', args, success, null, false );

                // don't let people send multiple grab records (at least prevent most of them);
                document.grabbed_items[document.grabbed_items.length] = content_id + "_grabbed";
        }
}

function newAjaxCommentEdit( content_id, new_message ) {
	var args = 'id='+content_id+'&message='+escape(new_message);
	newAjaxCall( 'cabbage', 'comment_edit', args, commentEditSuccess, commentEditFailure, content_id );
}

function commentEditSuccess( s_message, s_id ) {
	$('message_'+s_id).innerHTML = $('textarea_'+s_id).value;
	$('message_'+s_id).show();
	$('textarea_'+s_id).hide();
	$('status_'+s_id).innerHTML = 'Successfully edited.';
	$('edit_'+s_id).innerHTML = 'Edit';
}

function commentEditFailure( s_message, s_id ) {
	$('status_'+s_id).innerHTML = 'Edit failed mysteriously.';
}

function newAjaxFavoriteAdd( content_id, content_type ) {
	var args = 'id='+content_id+'&type='+content_type;
	newAjaxCall( 'cabbage', 'favorite_add', args, favoriteAddSuccess, favoriteAddFailure, content_id );
}

function favoriteAddSuccess( s_message, s_id ) {
	$('favorite_'+s_id).innerHTML = 'Added to favorites.';
}

function favoriteAddFailure( s_message, s_id ) {
	$('favorite_'+s_id).innerHTML = ':(';
}

function newAjaxFavoriteDelete( id ) {
	var args = 'id='+id;
	newAjaxCall( 'cabbage', 'favorite_delete', args, favoriteDeleteSuccess, favoriteDeleteFailure, id );
}

function favoriteDeleteSuccess( s_message, s_id ) {
	$('favorite_'+s_id).innerHTML = '';
}

function favoriteDeleteFailure( s_message, s_id ) {
	$('favorite_'+s_id).innerHTML = ':(';
}

function newAjaxLogin( source, password, email ) {
	var args = 'password='+escape(password)+'&email='+escape(email);
	newAjaxCall( 'cabbage', 'login', args, loginSuccess, loginFailure, source );
	$('lightbox1').style.border='3px solid #ffcc80';
}

function loginSuccess( s_message, s_id ) {
	if (s_id == 'topleft') {
		$('login_error_'+s_id).innerHTML = '<span style="color: #2fed00">'+s_message+'</span>';
		$('lightbox1').style.border='3px solid #99ff00';
		window.location = "/my";
	} else if (s_id == 'norefresh') {
	} else {
		window.location.href=window.location.href;
	}
}

function loginFailure( s_message, s_id ) {
	$('lightbox1').style.border='3px solid #ff8080';
	$('login_error_'+s_id).innerHTML = s_message;
}

function newAjaxForgotPassword( email ) {
	var args = 'email='+escape(email);
	newAjaxCall( 'cabbage', 'forgotPassword', args, forgotPasswordSuccess, forgotPasswordFailure, null );
}

function forgotPasswordSuccess( s_message, s_id ) {
	$('fp_indicator').style.display="none";
	$('fp_message').style.border="2px solid #99ff00";
	$('fp_message').style.backgroundColor="#ccff80";
	$('fp_message').style.display="block";
	$('fp_form').style.display="none";
	$('fp_message').innerHTML = s_message;
}

function forgotPasswordFailure( s_message, s_id ) {
	$('fp_indicator').style.display="none";
	$('fp_message').style.border="2px solid #ff0000";
	$('fp_message').style.backgroundColor="#ff8080";
	$('fp_message').style.display="block";
	$('fp_submit').disabled=false;
	$('fp_message').innerHTML = s_message;
}

function newAjaxResetPassword( email, token, password, password_confirm ) {
	var args = 'email='+escape(email)+'&token='+escape(token)+'&password='+escape(password)+'&password_confirm='+escape(password_confirm);
	newAjaxCall( 'cabbage', 'resetPassword', args, resetPasswordSuccess, resetPasswordFailure, null );
}

function resetPasswordSuccess( s_message, s_id ) {
	$('fp_indicator').style.display="none";
	$('fp_message').style.border="2px solid #99ff00";
	$('fp_message').style.backgroundColor="#ccff80";
	$('fp_message').style.display="block";
	$('fp_form').style.display="none";
	$('fp_message').innerHTML = s_message;
}

function resetPasswordFailure( s_message, s_id ) {
	$('fp_indicator').style.display="none";
	$('fp_message').style.border="2px solid #ff0000";
	$('fp_message').style.backgroundColor="#ff8080";
	$('fp_message').style.display="block";
	$('fp_submit').disabled=false;
	$('fp_message').innerHTML = s_message;
}

function newAjaxSignup( name, email, password, password_confirm, terms, captcha ) {
	$('su_submit').disabled = true;
	$('su_message').innerHTML = 'Please wait';
	$('su_message').style.color = '#000000';

	terms = terms ? 'yes' : 'no';
	var args = 'py_un='+escape(name)+'&py_ea='+escape(email)+'&py_pw='+escape(password)+'&py_pw_cf='+escape(password_confirm)+'&py_ts='+escape(terms)+'&py_cp='+escape(captcha);
	newAjaxCall( 'cabbage', 'signup', args, signupSuccess, signupFailure, null );
}

function signupSuccess( s_message, s_id ) {
	$('su_message').style.color = '#2d882d';
	$('su_message').innerHTML = 'Success! Check your email';
	newAjaxLogin( 'norefresh', $('py_pw').value, $('py_ea').value );
}

function signupFailure( s_message, s_id ) {
	$('su_message').style.color = '#ff0000';
	$('su_submit').disabled = false;

	if (s_message == 'captcha') { 
		$('su_cp').src = '/m/php/vendors/freecap/freecap_moo.php?cat='+Math.random();
		$('py_cp').value = '';
	}
	$('su_message').innerHTML = s_message;
}

	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 searchSubmit(a) {
		if (a!='all') {
			var ss = document.getElementById( 'pyzss' );
			var theval = ss.options[ss.selectedIndex].value;
			if (theval == 'zzzall')
				theval = 'all';
		} else {
			theval = a;
		}
		var q = document.getElementById('pyzq').value.toLowerCase().trim();
		if (q == '') {
			document.getElementById('pyzq').style.border = '1px solid red';
			document.getElementById('search_error').style.display='inline';
			return false;
		}

		window.location.href='/search/'+theval+'/'+q;
	}

	function submitenter(myfield,e)
	{
		var keycode;
		
		if (window.event) 
			keycode = window.event.keyCode;
		else if (e) 
			keycode = e.which;
		else 
			return true;
			
		if (keycode == 13)
		{
			searchSubmit('wtf');
			return false;
		} else
			return true;
	}    

