if (typeof(console) == "undefined") {
    console = {};
    console.log = function(message) {
        /*alert(message);*/
    }
}
else if (!Prototype.Browser.IE) {
    console.log = console.log.wrap(
        function(callOriginal) {
            var date = new Date();
            var time = ['getHours', 'getMinutes', 'getSeconds'].map(function (func) { return date[func](); }).map(function (num) { return num.toPaddedString(2); }).join(':') + "." + date.getMilliseconds().toString().truncate(2, "");

            var args = $A(arguments);
            args.shift() // remove callOriginal
            args.unshift(time);

            callOriginal.apply(callOriginal, args);
        }
    );
}


function remove_referral(div_id,rid,owner_id,referral_uid) {
   $(div_id).innerHTML = '<p align=center>nuking..</p>';

   var _url = "/a_referral.php?rid="+rid+"&u="+owner_id+"&remove="+referral_uid;
	/* alert(_url);

	return; */

   new Ajax.Updater(div_id, _url, {
      method: 'get'
   });
}

function set_home_page_type(val) {
    pageTracker._trackEvent('homepage', 'switch', String(val));

    new Ajax.Request("/a_homepage.php", {
            method: 'get',
            parameters: { htype: val },
            onSuccess: function(response) {
                window.location.reload(); 
            }
    });
    return false;
}

function track_window(track_id) {
    var div_id = 'autoplay_track';
    if(eval($(div_id))) {
        $(div_id).innerHTML = '';
        $(div_id).visibility = 'hidden';
    }

    twin = window.open('/play_track.php?t=' + track_id,
                       '_lc_track',
                       'dependent=no,directories=no,hotkeys=no,menubar=no,status=no,toolbar=no,location=no,resizable=yes,width=600,height=475');
    try { 
        twin.focus();
    } catch (e1) {
    }
    return twin;
}

function text_link_photo(owner,id,aid,tn_img_url) {
	var _link = "http://fubar.com/photo.php?u="+owner+"&i="+id+"&albumid="+aid;
	var _data = "<a href=\"" +_link+ "\" target=_blank>[ fubar.com photo: " + id + " ]</a>";
	return(_data);
}

function tn_link_photo(owner,id,aid,tn_img_url) {
	var _link = "http://fubar.com/photo.php?u="+owner+"&i="+id+"&albumid="+aid;
	var _data = "<a href=\"" +_link+ "\" target=_blank><img src=\"" +tn_img_url+ "\" border=0></a>";
	return(_data);
}

function text_link_raw_photo(owner,id,aid,tn_img_url) {
	var _link = "http://fubar.com/photo.php?u="+owner+"&i="+id+"&albumid="+aid;
	var _data = '';
	return(_data);
}

function tn_link_raw_photo(owner,id,aid,tn_img_url) {
	var _link = "http://fubar.com/photo.php?u="+owner+"&i="+id+"&albumid="+aid;
	var _data = '';
	return(_data);
}

function show_share_box(dest_link,mtype,suffix,shareInvite) {
	var _html = '';

	var _share_box_name = 'share_box_';
	if (suffix != null)
	{
		_share_box_name = _share_box_name + suffix
	}

	if(shareInvite == null){
		shareInvite = 0;
	}

	//alert('dest_link='+dest_link+' mtype='+mtype);
	
	__html = "<p>wtf!</p>";
	_html =
				
				"<form id='wtf' name='wtf'>" +
				"<table class='share_box'>" +
				"<tr><td class='share_box_hdr' colspan=5>Share this "+mtype+" with:</td></tr>" +
				"<input type=hidden id='mtype' name='mtype' value='"+mtype+"'>" +
				"<input type=hidden id='link' name='link' value='"+dest_link+"'>" +
				"<tr><td class='share_box_opts_all' align='right'>" +
				"All</td><td class='share_box_opts' align='right'>Family" + "</td>" + "<td class='share_box_opts'>"+
				"Friends</td><td class='share_box_opts'>Contacts" + "</td></tr>" +
				"<tr><td class='share_box_opts_all' align='right'>" +
				"<input name='all' type=checkbox></td><td class='share_box_opts' align='right'><input name='family' type=checkbox CHECKED>" +
				"</td>" +
				"<td class='share_box_opts'>"+
				"<input name='friends' type=checkbox></td>" +
				"<td class='share_box_opts'><input name='contacts' type=checkbox CHECKED>" +
				"</td></tr>" +
				"<tr><td class='share_box_input' colspan=5>Optional Email(s): <input type=text size=14 maxlength=200 name=email id=email>";
        if(shareInvite == 1){
	_html += "<br><input type='checkbox' name='shareInvite' id='shareInvite' value='1' checked> Invite my friends to fubar</td></tr>";
	}else{
	_html += "<input type='hidden' name='shareInvite' id='shareInvite' value='0'></td></tr>";
	}

	_html +=		"<tr><td class='share_box_opts' colspan=5>" + dest_link + "</td></tr>" +
				"<tr><td class='share_box_submit' colspan=5>" +
				"<center><input type=button value='share!' onclick='javascript:share_submit(\"" +
				suffix +
				"\");'></center>" +
				"</td></tr></table>" +
				"</form>";

	__html = "<table class='share_box'><tr><td>hi!</td></tr></table>";

    $(_share_box_name).innerHTML = _html;
}

function no_load_photo_comments(div_id,u,i) {
}

function load_photo_comments(div_id,u,i,idx) {
	//alert('loading photo comments.. div_id: '+div_id);
    $(div_id).innerHTML = '<br><br><p align=center style="padding-left:3em;font-weight:bold;color:red;">... LOADING ...</p>';

    new Ajax.Request("/a_profile_comments.php", {
            method: 'get',
            parameters: { u: u, i: i, idx: idx, type: 'photo' },
            onSuccess: function(response) {
                handle_comment_reformt(div_id,response);
            }
    });
}

function pimp_hand(div_id,owner,cmd) {
	$(div_id).innerHTML = '<p align=center>smackin this mofo.... one second..</p>';

	var _url = "/a_pimp_hand.php?owner="+owner+"&cmd="+cmd;
	new Ajax.Updater(div_id, _url, {
		method: 'get'
	});
}

function cherry_bomb(div_id,owner,albumid) {
	$(div_id).innerHTML = '<p align=center>wreckin this mofo.... one second..</p>';

	var _url = "/a_cherry_bomb.php?owner="+owner+"&albumid="+albumid;
	new Ajax.Updater(div_id, _url, {
		method: 'get'
	});
}

function comment_reply(type, ouid, id1, id2, cid, sess, ver) {
    if ($('comment_reply_comment_'+id1+"_"+id2+"_"+cid).visible()) {
        $('comment_reply_comment_'+id1+"_"+id2+"_"+cid).hide();
    } else {
        $('comment_reply_comment_'+id1+"_"+id2+"_"+cid).update('<br><br><p align=center style="padding-left:3em;font-weight:bold;color:red;">... LOADING ...</p>');
        $('comment_reply_comment_'+id1+"_"+id2+"_"+cid).show();

        new Ajax.Request('/a_profile_comments.php', {
            method: 'get',
            parameters: { action: 'reply', type: type, ouid: ouid, id1: id1, id2: id2, cid: cid, sess: sess, ver: ver },
            onSuccess: function(response) {
               handle_comment_reply(id1,id2,cid,response);
            }
        });
    }
}

function handle_comment_reply(id1,id2,cid,transport) {
    if (transport.status == 200) {
        var data = transport.responseJSON;
        if (data) {
            if (data['error']){
                alert("Unknown Error\n"+data['error']+"\n"+data['html']);
            } else {
                $('comment_reply_comment_'+id1+"_"+id2+"_"+cid).update(data['html']);
            }
        } else {
            $(div_id).update("Sorry, try again later");
        }
    } else {
        $(div_id).update("Sorry, try again later");
    }
}

function add_comment(id1, id2, obj, cid, div) {
    if (!cid) {
        cid = 0;
    }
    cid = Number(cid);

    var comment_div = $('new_comment_block_'+id1+'_'+id2);
    if (comment_div){
        // Show loading bar before AJAX returns
        var img_div = new Element('div').setStyle({
            textAlign: 'center',
            width: '100%',
            paddingTop: '20px',
            paddingBottom: '20px'
        });

        comment_div.update(img_div);
    }

    // AJAX to post new comment, and get result
    new Ajax.Request('/a_add_comment.php', {
        parameters: $('comment_frm_'+cid).serialize(true),
        onComplete: function(transport) { 
            if (transport.status == 200) {
                var data = transport.responseJSON;
                if (data) {
                  if (data['error']){
                    if (comment_div) {
                        comment_div.update("");
                    }
                    var tmp = $('comment_upsell_section_'+cid);
                    if (tmp) tmp.hide();
                    switch (data['error']){
                        case 1: // Generic Error
                            $('comment_error_'+cid).update(data['html']);
                            $('comment_error_'+cid).show();
                            break;
                        case 2: // Captcha Check
                        case 3: // Session Expired
                            $('comment_captcha_'+cid).show();
							$('comment_captcha_img_'+cid).update('<center style="padding-left:3em;font-weight:bold;color:red;">... LOADING ...</center>');

                            update_captcha('comment_captcha_img_'+cid, 'comment_captcha_img');
                            break;
                        case 4: // Approval Needed
                            $('comment_frm_'+cid).hide();
                            $('comment_error_'+cid).update(data['html']);
                            $('comment_error_'+cid).show();
                            $('comment_submit_wrapper_'+cid).hide();
                            $('comment_upsell_section_'+cid).hide();
                            break;
                        default:
                            alert("Unknown Error\n"+data['error']+"\n"+data['html']);
                            break;
                    }
                  }else{
                    $('comment_captcha_'+cid).hide();

                    if (comment_div){
                        comment_div.update(data['html']);
                    }

                    comment_reformt('comment_'+id1+'_'+id2,data['html']);

                    var tmp = $('empty_comments_msg');
                    if (tmp) {
                        tmp.hide();
                    }
                    if (data['points'] && data['points'] != 0) {
                        $('comment_wrapper_'+cid).update("Your comment was added and you have been awarded +"+data['points']+" points!");
                    } else {
                        $('comment_wrapper_'+cid).update("Your comment was added.");
                    }
                    $('comment_wrapper_'+cid).show();

                    $('comment_frm_'+cid).hide();
                    
                    var tmp = $('comment_upsell_section_'+cid);
                    if (tmp) tmp.hide();

                    if ($('comment_error_'+cid)) {
                        $('comment_error_'+cid).hide();
                    }

                    if (pageTracker && (typeof data['to_life'] != 'undefined')) {
                        pageTracker._trackEvent('newcomment_'+transport.request.parameters.type, 'recv', String(data['to_life']));
                    }
                    if (pageTracker && (typeof data['from_life'] != 'undefined')) {
                        pageTracker._trackEvent('newcomment_'+transport.request.parameters.type, 'sent', String(data['from_life']));
                    }    
                    
                    document.disableReplies = true;
                  }
                }
            }
        }
    });

    return false;
}

var captcha_shown = new Array();
function update_captcha(id,label) {
    if (typeof label == 'undefined') {
        label = id;
    }
    
	if (typeof pageTracker != 'undefined') {
		if (!captcha_shown[id]) {
			captcha_shown[id] = 1;
			pageTracker._trackEvent(label, 'Action::captcha_shown');
		}
		else {
			pageTracker._trackEvent(label, 'Action::captcha_refresh');
			captcha_shown[id]++;
		}
	}
	var host = (("https:" == document.location.protocol) ? "https://fubar.com" : "");
	new Ajax.Updater(id, host+'/a_getcaptcha.php', {method: 'get'});
}

function share_submit(suffix) {
	var form_id = 'wtf';
	var _friends=1;
	var _fans=1;
	var _family=1;
	var _all=1;
	var _contacts=1;
	var _emails='';
	var _mtype='';
	var _link='';
	var _share_box_name = 'share_box_';
	var _shareInvite=0;
	if (suffix != null)
	{
		_share_box_name = _share_box_name + suffix;
	}

	if(! $(form_id).all.checked) _all=0;
	if(! $(form_id).family.checked) _family=0;
	if(! $(form_id).friends.checked) _friends=0;
	_fans = 0;
	if(! $(form_id).contacts.checked) _contacts=0;
	if($(form_id).email.value) _emails=$(form_id).email.value;
	if($(form_id).mtype.value) _mtype=$(form_id).mtype.value;
	if($(form_id).link.value) _link=$(form_id).link.value;
	if($(form_id).shareInvite.checked){
		 _shareInvite=$(form_id).shareInvite.value;
	}else{
		_shareInvite=0;
	}

	$(_share_box_name).innerHTML = 'sharing... one sec...';
    new Ajax.Updater(_share_box_name, '/share.php', {
            method: 'post',
            parameters: { all: _all, family: _family, friends: _friends, fans: _fans, contacts: _contacts, email:_emails, mtype:_mtype, link:_link, shareInvite:_shareInvite }, 
            onComplete: function(transport) { if (transport.status != 200) {
                                                $(_share_box_name).innerHTML = 'error sharing!';
                                              }
        }
    });

    return true;
}

function show_photo_links(owner,photo_id,album_id,tn_img_url) {
	var textarea_size = "rows=5 cols=40";
	var div_id = 'image_links';
	var to_this_page_tn = tn_link_photo(owner,photo_id,album_id,tn_img_url);
	var to_this_page = text_link_photo(owner,photo_id,album_id,tn_img_url);
	var image_only = text_link_raw_photo(owner,photo_id,album_id,tn_img_url);
	var image_only_tn = tn_link_raw_photo(owner,photo_id,album_id,tn_img_url);
	var _html =
		'<table class=\"blue_box\" align=center width=90%><tr><td>' +
		'<table border=0 align=center width=100% cellpadding=0 cellspacing=0 border=0><tr><td><p class=\"image_links_desc\" align=center>' +
		'Cut &amp; Paste the links below into your blog or webpage to create a link back to this photo page! If you want people to see and click on a thumbnail of this photo, use the HTML code on the left. If you want people to see and click on a text link, use the HTML code on the right.</p></td></tr></table>' +
		'<table class=\"image_links\" style=\"padding-bottom:5em;\" align=center>\n' +
		'<tr>' + 
		'<td class=\"image_links_hdr\">with a <font color=red>thumbnail link</font>..</td>' +
		'<td class=\"image_links_hdr\">..or with a <font color=red>text link</font>.</td>' + 
		'</tr>\n' +
		'<tr><td style=\"padding-right:1em;\">' + 
		'<textarea ' + textarea_size + '>' + 
		to_this_page_tn +
		'\n</textarea>\n' +
		'</td><td style=\"padding-left:1em;\">' +
		'<textarea ' +textarea_size+ '>' +
		to_this_page +
		'\n</textarea>\n' +
		'</td></tr>' +
		'<tr><td class=\"image_links_hdr\">preview:</td><td class=\"image_links_hdr\">preview:</td></tr>' +
		'<tr><td class=\"image_links_hdr\">' + to_this_page_tn + '</td><td class=\"image_links_hdr\" valign=top>' + to_this_page + '</td></tr>' +
		'<tr><td class=\"image_links_hdr\" colspan=2><center><br><a href=\"javascript:hide_photo_links();\">hide this link box</a></td></tr>' + 
		'</table>' +
		'</td></tr></table><br><br>';


	// alert(_html);

	$(div_id).innerHTML = _html;
	$(div_id).style.visibility = 'visible';
}
function hide_photo_links() {
	var div_id = 'image_links';
	$(div_id).innerHTML = '';
	$(div_id).style.visibility = 'hidden';
}

function prompt_text(name,mtype,header,contents) {
	var newtext = prompt(header,contents);
	if(! newtext) {
		return;
	}
	// theObj = document.getElementByID(name)
	// theObj = document.all(name);
	theObj = $(name);
	if(mtype == "image") {
		// document.lcform.body.value += "<img src=\"" + newtext + "\">";
		theObj.value += "<img src=\"" + newtext + "\">";
	} else if(mtype == "link") {
		theObj.value += "<a href=\"" + newtext + "\" target=_blank>" + newtext + "</a>";
	} else if(mtype == "music") {
		theObj.value += "music: " + newtext;
	} else if(mtype == "movie") {
		theObj.value += "movie: " + newtext;
	}
}

function MM_goToURL() { //v3.0
    var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
    for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function validateemail(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}


function toggleVisibility(id) {
    identity = document.getElementById(id).className;
    identity2 = document.getElementById(id);
    if(identity == "hide"){
        identity2.className = "show";
    }else{
        identity2.className = "hide";
    }
}

function commentModVisible(id) {
    var tmpdiv = $(id);
    if (tmpdiv) {
        var ances = tmpdiv.ancestors();
        for (var index = 0; index < ances.length; ++index) {
            var item = ances[index];
            if (item.hasClassName('resizedCommentArea')) {
                var twidth = item.getWidth()-tmpdiv.getWidth()-66;
                tmpdiv.setStyle({left: twidth+'px'}); 
                break;
            }
        }

        tmpdiv.show();
    }

}

function toggleClassVisible(id) {
    var tmpdiv = $(id);
    if (tmpdiv) {
        tmpdiv.show();
    }
}

function toggleClassHidden(id) {
    var tmpdiv = $(id);
    if (tmpdiv) {
        tmpdiv.hide();
    }
}

function toggleDisplay(id) {
    var tmpdiv = $(id);
    if (tmpdiv) {
        if (tmpdiv.visible()) {
            tmpdiv.hide();
        } else {
            tmpdiv.show();
        }
    }
}

function fuckcheckall(e) {
	var f = e.form, z = 0;
   for(z=0; z<f.length;z++){
   	if(f[z].type == 'checkbox' && f[z].name != 'checkall') {
   		f[z].checked = e.checked;
      }
   }
}

function checkall(e, check) {
	var f = e.form, z = 0;

   for(z=0; z<f.length;z++){
   	if(f[z].type == 'checkbox' && f[z].name != 'checkall') {
		if (check == true)
		{
   			f[z].checked = true;
		}
		else
		{
   			f[z].checked = false;
		}
      }
   }
}

function checkRadioAll(e, x) {
   var f = $('msgs')

   for(var z=0; z<f.length;z++){
    if(f[z].type == 'radio') {
        if (f[z].value == x) {
	   	    f[z].checked = true;
	    }
    }
   }
}

function toggle_checkboxes(button, prefix) {
  var val = button.checked;
  for (var i=1; ; ++i) {
    var el = document.getElementById(prefix+i);
    if (!el) break;

    el.checked = val;
  }
  var ck = document.getElementById(prefix+'_top');
  if (ck) ck.checked = val;
  ck = document.getElementById(prefix+'_bottom');
  if (ck) ck.checked = val;
}

function submit_checked(prefix, script, sep) {
  if (!sep) sep = ',';

  var dels = new Array();
  for (var i=1; ; ++i) {
    var el = document.getElementById(prefix+i);
    if (!el) break;

    if (el.checked) {
      dels.push(el.name);
    }
  }

  if (dels.length == 0) {
    alert("You must select some gifts before you can delete them.");
  } else if (confirm("Ok to delete "+dels.length+" gifts?")) {
    window.location.href = script+dels.join(sep);
  }
}


function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
  if(document.getElementById(d).style.display == "none") { 
	document.getElementById(d).style.display = "block"; 
  } else { 
	document.getElementById(d).style.display = "none"; 
  } 
}


function share_email_submit() {
    var form_id = 'emailform';
    var _emails='';
    var _mtype='';
    var _link='';
    var _friends=0;
    var _fans=0;
    var _family=0;
    var _all=0;
    var _contacts=0;
    var _shareitem_id='';
    var _ownerid='';
    var _ftype = '';
    var _upload = '';
    var _redirect = '';
    var _from = '';
    var _shareInvite = '';
    var _msg = '';
    var _sub = '';
    
    var email_list = new Array();
    var add_list   = new Array();

    if($(form_id).email){
        _emails=$(form_id).email.value;
    }else{
        for (var i = 0; i < $(form_id).elements.length; i++) {
            if ( $(form_id).elements[i].name.indexOf('email')!=-1 && 
                 $(form_id).elements[i].checked == true && 
                 $(form_id).elements[i].name != 'select_all_email' && 
                 $(form_id).elements[i].name != 'select_all_add'
               ) 
            {
                email_list.push($(form_id).elements[i].value);
            }

            if ( $(form_id).elements[i].name.indexOf('add')!=-1 && 
                 $(form_id).elements[i].checked == true && 
                 $(form_id).elements[i].name != 'select_all_email' && 
                 $(form_id).elements[i].name != 'select_all_add'
               ) 
            {
                add_list.push($(form_id).elements[i].value);
            }
        }
    }

    if($(form_id).mtype) _mtype=$(form_id).mtype.value;
    if($(form_id).link) _link=$(form_id).link.value;
    if($(form_id).subject) _sub=$(form_id).subject.value;
    if($(form_id).message) _msg=$(form_id).message.value;
    if($(form_id).ownerid) _ownerid=$(form_id).ownerid.value;
    if($(form_id).shareitem_id) _shareitem_id=$(form_id).shareitem_id.value;
    if($(form_id).ftype) _ftype=$(form_id).ftype.value;
    if($(form_id).upload) _upload=$(form_id).upload.value;
    if($(form_id).redirect) _redirect=$(form_id).redirect.value;
    if($(form_id).from) _from=$(form_id).from.value;
    if($(form_id).shareInvite) _shareInvite=$(form_id).shareInvite.value;

    new Ajax.Updater('internalInviteWrapper', '/share.php', {
        method: 'post',
        parameters: { all:_all, 
                      family:_family, 
                      friends:_friends,
                      fans:_fans,
                      contacts:_contacts,
                      email:_emails,
                      email_list:email_list.join(';'),
                      add_list:add_list.join(';'),
                      mtype:_mtype,
                      link:_link,
                      msg:_msg,
                      ownerid:_ownerid,
                      subject:_sub,
                      ftype:_ftype,
                      upload:_upload,
                      shareitem_id:_shareitem_id,
                      from:_from,
                      shareInvite:_shareInvite
                    }, 
        onComplete: function(transport) { 
            if (transport.status == 200) {
                if(_upload == 1)
                    setTimeout( "window.parent.location='/myimages.php'", 3000 );
            }
        } 
    });

    return true;
}

function share_contest_submit(suffix) {
        var form_id = 'wtf';
        var _emails='';
        var _mtype='';
        var _link='';
        var _friends=0;
        var _fans=0;
        var _family=0;
        var _all=0;
        var _contacts=0;
        var _share_box_name = 'share_box_';
        var _redirect = '';
	var _sendername = '';
	var _msg = '';
	var _thumbnail = '';

        if (suffix != null)
        {
                _share_box_name = _share_box_name + suffix;
        }
        if($(form_id).email.value) _emails=$(form_id).email.value;
        if($(form_id).mtype.value) _mtype=$(form_id).mtype.value;
        if($(form_id).link.value) _link=$(form_id).link.value;
        if($(form_id).msg.value) _msg=$(form_id).msg.value;
        if($(form_id).redirect.value) _redirect=$(form_id).redirect.value;
	if($(form_id).sendername.value) _sendername=$(form_id).sendername.value;
	if($(form_id).thumbnail.value) _thumbnail=$(form_id).thumbnail.value;
        $(_share_box_name).innerHTML = 'sharing... one sec...';

    new Ajax.Updater(_share_box_name, '/share.php', {
            method: 'post',
            parameters: { all:_all, family:_family, friends:_friends, fans:_fans, contacts:_contacts, email:_emails, mtype:_mtype, link:_link, msg:_msg, sendername:_sendername, thumb:_thumbnail },
            onComplete: function(transport) { if (transport.status != 200) {
                    $(_share_box_name).innerHTML = 'error sharing!';
                   }
        }
   });

   return true;
}

function send_to_clipboard(text2copy) {
	if (window.clipboardData) {
		window.clipboardData.setData("Text",text2copy);
		} else {
			var flashcopier = 'flashcopier';
			if(!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}







/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
        var dumped_text = "";
        if(!level) level = 0;   

        //The padding given at the beginning of the line.
        var level_padding = "";
        for(var j=0;j<level+1;j++) level_padding += "    ";
        
        if(typeof(arr) == 'object') { //Array/Hashes/Objects
            for(var item in arr) {
                var value = arr[item];
                
                if(typeof(value) == 'object') { //If it is an array,
                    dumped_text += level_padding + "'" + item + "' ...\n";
                    dumped_text += dump(value,level+1);
                } else {
                    dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
                }
            }
        } else { //Stings/Chars/Numbers etc.
            dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
        }
        return dumped_text;
}

function hide_homepage_supportBox(){	
		hide_homepage_box('homepage_support_box','hsb');
}

function hide_homepage_creditsBox(){	
		hide_homepage_box('credits_promo_box','hcb');
}

function hide_homepage_vipBox(){	
		hide_homepage_box('vip_promo_box','hvb');
	
}

function hide_homepage_box(div_id, query_str){
	var myhash = new Hash();
	myhash.set(query_str, 1);

	$(div_id).hide();
    
    new Ajax.Request('/a_homepage.php', {
            method: 'get',
            parameters:myhash
    });
}



function is_numeric(str)
{
        var valid_chrs = "0123456789.";
        var is_number = true;
        var chr;


        for (i = 0; i < str.length && is_number == true; i++)
        {
                chr = str.charAt(i);
                if (valid_chrs.indexOf(chr) == -1)
                {
                        is_number = false;
                }
        }
        return is_number;
}

function checkNumber(input, min, max, msg)
{
    msg = msg + " field has invalid data: " + input.value;

    var str = input.value;
    for (var i = 0; i < str.length; i++) {
        var ch = str.substring(i, i + 1)
        if ((ch < "0" || "9" < ch) && ch != '.') {
            alert(msg);
            return false;
        }
    }
    var num = 0 + str;
    if (num < min || max < num) {
        alert(msg + " not in range [" + min + ".." + max + "]");
        return false;
    }
    input.value = str;
    return true;
}

function getMonthLength(month,year,julianFlag)
{
   var ml;
   if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10||month==12)
      {ml = 31;}
   else {
       if(month==2) {
          ml = 28;
          if(!(year%4) && (julianFlag==1 || year%100 || !(year%400)))
             ml++;
       }
       else
          {ml = 30;}
   }
   return ml;
}
function computeForm(yr,mon,day)
{
//   var ml={31,28,31,30,31,30,31,31,30,31,30,31};

   MNames=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep",
      "Oct","Nov","Dec");

   var today = new Date();

   var yd = today.getFullYear();
   var md = today.getMonth()+1;
   var dd = today.getDate();
   var yb = yr;
   var mb = mon;
   var db = day;
   // Month length 0->use calendar length
   var mLength =0;
   // 0 if Gregorian, 1 is Julian
   var isJulian =0;

   var ma=0;
   var ya=0;

   var da = dd-db;
   // This is the all-important day borrowing code.
   if(da<0)
   {
      md--;
      // Borrow months from the year if necesssary.
      if(md<1)
      {
         yd--;
         // Determine no. of months in year
         if(mLength)
            {md=md+parseInt(365/mLength);}
         else
            {md=md+12;}
      }
      if(mLength==0) // Use real month length if no fixed
      {              // length is indicated - note that we add a leap day if necessary.
         ml=getMonthLength(md,yd,isJulian);
         da=da+ml;
      }
      // For this case, everything works like it did in elementary school.
      else
         {da+=mLength;} // Use fixed month length
   }

   ma = md - mb;
   // Month borrowing code - borrows months from years.
   if(ma<0)
   {
      yd--;
      if(mLength!=0)
         {ma=ma+parseInt(365/mLength);}
      else
         {ma=ma+12;}
   }

   ya = yd - yb;


return ya;
}


function confirmSubmit(valstr)
{
    var agree=confirm(valstr);
    if (agree)
        return true;
    else
        return false;
}

function setCookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;

}

function getCookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

function deleteCookie ( cookie_name )
{
    var cookie_date = new Date ( );  // current date & time
    cookie_date.setTime ( cookie_date.getTime() - 1 );
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function load_owned_comments(div_id,u,idx) {
    $(div_id).innerHTML = '<br><br><p align=center style="padding-left:3em;font-weight:bold;color:red;">... LOADING ...</p>';

    new Ajax.Request("/a_profile_comments.php", {
        method: 'get',
        parameters: { u: u, idx: idx, type: 'owned' },
        onSuccess: function(response) {
            handle_comment_reformt(div_id,response);
        }
    });

   return true;
}

// This function should only be called on dom:loaded
function show_lb(){
    var querystring = window.location.querystring;
    var temp = querystring['useLb'];
    if (temp) {
        lightboxActive();
        open_lightbox_manual(unescape(temp));
        return true;
    }
    var temp = querystring['npw'];
    if (temp) {
        if (document.location.href.indexOf("/home.php") != -1) { 
            lightboxActive();
			var step = querystring['step'] || 1;
            var ver = querystring['ver'] || 0;
            open_lightbox_manual("/lb_profilewizard_wrapper.php?s="+step+"&ver="+ver,function() { window.location = "/home.php" });
            return true;
        }
    }
    /*
    var temp = querystring['sud'];
    if (temp) {
        if (document.location.href.indexOf("/home.php") != -1) {
            lightboxActive();
            open_lightbox_manual("/lb_homeonlinedrink.php", function() { window.location = "/home.php" });
            return true;
        }
    }  
    */
    return false;
}

function photo_nav_over(id,nsfw,newicon){
	if(id == 0){
        var navid = 'default_photonav';
        var iconid = 'default_photoicon';
	var icon2id = 'default_photoicon_unselected';
        var linkid = 'default_photolink';
	}else{
	var navid = 'photonav_'+id;
	var iconid = 'photoicon_'+id;
	var icon2id = 'photoicon_unselected_'+id;
	var linkid = 'photolink_'+id;
	}

	if(newicon == 1){
	    var newicon1 = 'newicon_selected_'+id;
        var newicon2 = 'newicon_unselected_'+id;
	    var newiconid = 'newicon_'+id;

	    $(newiconid).style.backgroundColor = '#666666';	
	    toggleVisibility(newicon1);
        toggleVisibility(newicon2);
	}

	var linktext = 'photonavlink_'+id;
	if(nsfw == 1){
//	$(iconid).innerHTML = '<img src="/imgs/folderOpenNSFW.gif" width="17" height="17" hspace="0" vspace="0" border="0">';
        toggleVisibility(iconid);
        toggleVisibility(icon2id);
	$(navid).style.backgroundColor = '#666666';
        $(linkid).style.backgroundColor = '#666666';
	}else{
	toggleVisibility(iconid);
	toggleVisibility(icon2id);
        //$(iconid).innerHTML = '<img src="/imgs/folderOpen.gif" width="17" height="17" hspace="0" vspace="0" border="0">';
        $(navid).style.backgroundColor = '#666666';
        $(linkid).style.backgroundColor = '#666666';
	}
	$(linktext).style.color = '#000';
}

function photo_nav_out(id,nsfw,newicon){

	if(id == 0){
        var navid = 'default_photonav';
        var iconid = 'default_photoicon';
	var icon2id = 'default_photoicon_unselected';
        var linkid = 'default_photolink';
        }else{
	var navid = 'photonav_'+id;
	var iconid = 'photoicon_'+id;
	var icon2id = 'photoicon_unselected_'+id;
	var linkid = 'photolink_'+id;
	}
	var linktext = 'photonavlink_'+id;

        if(newicon == 1){
            var newicon1 = 'newicon_selected_'+id;
            var newicon2 = 'newicon_unselected_'+id;
            var newiconid = 'newicon_'+id;

            $(newiconid).style.backgroundColor = 'transparent';
            toggleVisibility(newicon1);
            toggleVisibility(newicon2);
        }

	if(nsfw == 1){
	//$(iconid).innerHTML = '<img src="/imgs/folderClosedNSFW.gif" width="17" height="17" hspace="0" vspace="0" border="0">';
        toggleVisibility(iconid);
        toggleVisibility(icon2id);
	}else{
	toggleVisibility(iconid);
	toggleVisibility(icon2id);
        //$(iconid).innerHTML = '<img src="/imgs/folderClosed.gif" width="17" height="17" hspace="0" vspace="0" border="0">';
	}

	//$(navid).style.backgroundColor = '#000000';
    $(navid).style.backgroundColor = 'transparent';
	//$(linkid).style.backgroundColor = '#000000';
    $(linkid).style.backgroundColor = 'transparent';
	$(linktext).style.color = '#8e9193';
}

function handle_comment_reformt(div_id,transport) {
    if (transport.status == 200) {
        var data = transport.responseJSON;
        if (data) {
            if (data['error']){
                comment_reformt(div_id,data['html']);
            } else {
                comment_reformt(div_id,data['html']);       
            }
        } else {
            $(div_id).update("Sorry, please try again.");
        }
    } else {
        $(div_id).update("Sorry, please try again.");
    }
}

function checkExternalImageSize(img) {
  if (Prototype.Browser.IE) {
    if (img.hasClassName('fubarlimitimgsize')) {
        var dim = img.getDimensions();
        if ((dim.width > 300) || (dim.height > 300)) {
            if (dim.width > dim.height) {
                img.setStyle({ width: '300px' });
            } else {
                img.setStyle({ height: '300px' });
            }
        }
    }
  }
}


function comment_reformt(div_id,txt) {
    try {
                var div = $(div_id);

                if (!txt.empty()) {
                    div.update(txt);
                }

                var bwidth = div.getWidth();

                div.setStyle({ width: bwidth+'px', overflow: 'hidden' });
                div.addClassName('resizedCommentArea');

                //check all image sizes
                var imgs = div.getElementsBySelector('img');
                imgs.each(function(img) {
                    if (!img.hasClassName('fubaruserimage')) {
                        var url = img.src;
                        if (url.search('fubar.com') == -1) {
                            if (!img.hasClassName('fubarlimitimgsize')) {
                                img.addClassName('fubarlimitimgsize');
                            }
                        }                       
                    }
                });

                myLL.specialDelayLoad(div);
    } catch(e) {
        //ingore any issues
    }
}

function delete_comment(cid,id1,id2,type) {
    if (confirm("Delete this comment?")) {
        new Ajax.Request("/a_comment.php", {
            method: 'post',
            parameters: { cid: cid, id1: id1, id2: id2, type: type, cmd: 'delete' },
            onSuccess: function(response) {
                handle_delete_comment(response, type);
            },
            onComplete: event_helper.trigget_event('notify_count')
        });
    }
}

function handle_delete_comment(transport, type) {
    if (transport.status == 200) {
        var data = transport.responseJSON;
        if (data) {
            if (data['error']){
                alert(data['html']);
            } else {
                if (type == "blog") {
                    reload_blog_comments();
                } else if (type == "status") {
                    reload_status_comments();
                } else if (type == "mumm") {
                    reload_mumm_comments();
                } else if (type == "lounge") {
                    reload_lounge_comments();
                } else if (type == "profile") {
                    reload_profile_comments();
                } else {
                    window.location.reload();
                }
            }
        }
    }
}

function move_comment(cid,id1,id2,type) {
    if (confirm("Move this comment?")) {
        new Ajax.Request("/a_comment.php", {
            method: 'post',
            parameters: { cid: cid, id1: id1, id2: id2, type: type, cmd: 'move' },
            onSuccess: function(response) {
                handle_move_comment(response, type);
            }
        });
    }
}

function handle_move_comment(transport, type) {
    if (transport.status == 200) {
        var data = transport.responseJSON;
        if (data) {
            if (data['error']){
                alert(data['html']);
            } else {
                if (type == "blog") {
                    reload_blog_comments();
                } else {
                    window.location.reload();
                }
            }
        }
    }
}

function z_getScrollPositionForElement(elem){ // returns scroll top which is how far we have scrolled.
    var pos;
    if (self.pageYOffset){ // all except Explorer
          pos = elem.scrollTop;
    } else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict Mode
        pos = elem.scrollTop;
    } else if (document.body){ // other Explorers
          pos = elem.scrollTop;
    }
    return pos
}

function z_getHeightPositionForElement(elem){ // returns the height of the viewing area. This usually will be a constant.
    var h;
    if (self.innerHeight){ // all except Explorer
        h = elem.clientHeight;
    } else if (document.documentElement && document.documentElement.clientHeight){  // Explorer 6 Strict Mode
        h = elem.clientHeight;
    } else if (document.body){ // other Explorers
        h = elem.clientHeight;
    }
    return h;
}

// from http://www.quirksmode.org/viewport/compatibility.html
function z_getScroll(){ // returns how far down we are scrolled
    var pos;
    if (self.pageYOffset){ // all except Explorer
          pos = self.pageYOffset
    } else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict Mode
        pos = document.documentElement.scrollTop
    } else if (document.body){ // other Explorers
          pos = document.body.scrollTop
    }
    return pos
}

// from http://www.quirksmode.org/viewport/compatibility.html
function z_getHeight(){ // returns the height of the viewing area
    var h;
    if (self.innerHeight){ // all except Explorer
        h = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight){  // Explorer 6 Strict Mode
        h = document.documentElement.clientHeight;
    } else if (document.body){ // other Explorers
        h = document.body.clientHeight;
    }
    return h;
}

// from http://www.quirksmode.org/viewport/compatibility.html
function z_getWidth(){ // returns the width of the viewing area
    var h;
    if (self.innerWidth){ // all except Explorer
        h = self.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth){  // Explorer 6 Strict Mode
        h = document.documentElement.clientWidth;
    } else if (document.body){ // other Explorers
        h = document.body.clientWidth;
    }
    return h;
}


function clear_default_text(divid,deadarg,option) {
    var ret = false;

    var tmpele = $(divid);
    if (tmpele) {
        if (tmpele.hasClassName("defaultText")) {
            tmpele.clear();
            tmpele.removeClassName("defaultText");
            ret = true;
        }
    }

    if (option) {
        if (tmpele) {
            try {
                tmpele.focus();
            } catch(e) {
            }
        }    
    }

    return ret;
}

function replace_password_box(div1,div2) {
    var tmpele = $(div1);
    if (tmpele) {
        tmpele.hide();
    }
    tmpele = $(div2);
    if (tmpele) {
        tmpele.show();
        try {
            tmpele.focus();
        }catch(e1) {
        }
    }
}

// functions to resize textfields
function activateResize(elementId) {
    Event.observe(elementId, 'keyup', function() {
      updateSize(elementId)
    });          
    updateSize(elementId)
}                
                    
function updateSize(elementId) {
    var element = $(elementId); //look up the element once & reuse
     // alert(element.getHeight());
    if (element.getHeight() > 150){
        element.addClassName('scroll'); //create a .scroll class with overflow-y:scroll
    }else{
        //if scrollbars appear, make it bigger, unless it's bigger then the user's browser area.
        if(element.getHeight()< element.scrollHeight && element.getHeight()<document.viewport.getHeight()) {
            $(element).style.height = $(element).getHeight()+15+'px'
            if(Element.getHeight(element)<$(element).scrollHeight) {
                window.setTimeout("updateSize('"+element+"')",5)
            }                  
        }
    }   
}


function image_roll(tag,img) {
    tag.src = img;
}

function change(id, newClass) {
    identity=document.getElementById(id);
    identity.className=newClass;
}

function reload_captcha_image(captchaid) {
    new Ajax.Request("/a_reload_captcha.php",
    {
        method: 'post',
        onComplete: function(request) { reload_captcha_done(request,captchaid); }
    });
}

function reload_captcha_done(request,captchaid) {
    var data = request.responseJSON;
    if (data && data.option) {
        $('captchaFormWrapper_'+captchaid).show();
        if (!$('captcha_'+captchaid).hasClassName('required-captcha')) {
            $('captcha_'+captchaid).addClassName('required-captcha');
        }

        var tmpdiv = $('captchatoken_'+captchaid);
        if (tmpdiv && data.option.token) {
            tmpdiv.value = data.option.token;
        }
        tmpdiv = $('captchaimg_'+captchaid);
        if (tmpdiv && data.option.image) {
            tmpdiv.src = "/captchaimg.php?data="+data.option.image+"&i="+data.option.uid;
        }
        tmpdiv = $('sess_'+captchaid);
        if (tmpdiv && data.option.sess) {
            tmpdiv.value = data.option.sess;
        }
        tmpdiv = $('captcha_'+captchaid);
        if (tmpdiv) {
            tmpdiv.value = "";
        }
    }
}

function clear_crush(event) {
    if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            new Ajax.Request('/a_crush.php', {
                parameters: form.serialize(true),
                onSuccess: function(resp) {
                    clear_crush_response(resp);
                }
            });
        }
        Event.stop(event);
    }
    Modalbox.resizeToContent();
}

function clear_crush_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
                    Modalbox.insert_error_bottom(1,data.html);
                }
            } else {
                Modalbox.notification('Successfully removed crush', { autoClose: 3000} );
		window.location.reload();
            }
        }
    }

}

function add_crush(event) {
    if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            new Ajax.Request('/a_crush.php', {
                parameters: form.serialize(true),
                onSuccess: function(resp) {
                    add_crush_response(resp);
                }
            });
        }
        Event.stop(event);
    } else {
        Modalbox.resizeToContent();
    }
}

function add_crush_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
                    Modalbox.insert_error_bottom(1,data.html);
                }
            } else {
                Modalbox.notification('Successfully added crush', { autoClose: 3000} );
            }
        }
    }

}

/*
 * AJAX call to activate  a user bling.
 */

function mybling_activate(event) {
    if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            var obj = form.serialize(true);
            if(obj['m_action'] == 'Activate'){
                var hidden = form['paygift_id'];
                new Ajax.Request('/a_mybling_store_action.php', {
                   parameters: form.serialize(true),
                   onSuccess: function(resp) {
                     mybling_activate_response(resp);
                   }
               });
            }
            else {
		var paygift_id = obj['paygift_id'];
		$('bling_tooltip_action_activate_div').hide();
		var deleteLinkDiv = $('bling_tooltip_delete_link');
                var activateLinkDiv = $('bling_tooltip_activate_link');
                var favoriteLinkDiv = $('bling_tooltip_favorite_link');
                var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
		if(deleteLinkDiv != null){
                	deleteLinkDiv.show();
		}
		if(activateLinkDiv !=null){
                	activateLinkDiv.show();
		}
		if(favoriteLinkDiv != null && favoriteLinkDiv.readAttribute('status') != '0'){
			favoriteLinkDiv.show();
		}
		if(removeFavoriteLinkDiv != null){
			removeFavoriteLinkDiv.show();
		}
            }

        }
        Event.stop(event);

    } 
    
}


function removeActionMessage(div){
	var msgdiv = $(div);
	if(msgdiv != null){
	    msgdiv.hide();
	}
	var deleteLinkDiv = $('bling_tooltip_delete_link');
        var activateLinkDiv = $('bling_tooltip_activate_link');
        var favoriteLinkDiv = $('bling_tooltip_favorite_link');
        var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
	var polishDiv = $('bling_tooltip_action_remove_polish_div');
	
	if(deleteLinkDiv != null && deleteLinkDiv.readAttribute('status') != '0'){
        	deleteLinkDiv.show();
	}
        if(activateLinkDiv != null && activateLinkDiv.readAttribute('status') != '0'){
        	activateLinkDiv.show();
        }
	if(favoriteLinkDiv != null && favoriteLinkDiv.readAttribute('status') != '0' ){
        	favoriteLinkDiv.show();
        }
	if(removeFavoriteLinkDiv != null ){
        	removeFavoriteLinkDiv.show();
        }
	    if(polishDiv != null ){
                polishDiv.show();
            }
}
/*
 * AJAX response method to handle call mybling_activate
 */

function mybling_activate_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
			$('bling_tooltip_action_activate_div').hide();
        	        $('bling_action_message').show()
                	$('bling_action_message').update(data.html);
			removeActionMessage.delay(4, 'bling_action_message');
                }
            } else {
	
		var paygiftImg = response.request.parameters['paygift_img_active'];
		var paygiftId = response.request.parameters['paygift_id'];
		$('bling_'+paygiftId+'_img').writeAttribute('src', paygiftImg);
		$('newest_bling_'+paygiftId+'_img').writeAttribute('src', paygiftImg);
		if($('favorite_bling_'+paygiftId+'_img') != null){
			$('favorite_bling_'+paygiftId+'_img').writeAttribute('src', paygiftImg);
		}
		$('bling_'+paygiftId+'_tooltip_img').writeAttribute('src', paygiftImg);
		$('bling_tooltip_action_activate_div').hide();
		$('bling_tooltip_special_edition_status').update(data.option);
		var favoriteLink = $('bling_tooltip_favorite_link');
		if(favoriteLink != null && favoriteLink.readAttribute('status') != '0' ){
			favoriteLink.show();
		}
		var removeFavoriteLink = $('bling_tooltip_remove_favorite_link');
		if(removeFavoriteLink != null ){
			removeFavoriteLink.show();
		}
		var activateLinkDiv = $('bling_tooltip_activate_link');
		activateLinkDiv.writeAttribute('status',0);
		var deleteLinkDiv = $('bling_tooltip_delete_link');
		deleteLinkDiv.writeAttribute('status',0);

            }
        }
    }

}


function mybling_remove_favorite(event) {
   if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            var obj = form.serialize(true);
            if(obj['m_action'] == 'Remove'){
                new Ajax.Request('/a_mybling_store_action.php', {
                   parameters: form.serialize(true),
                   onSuccess: function(resp, form) {
                     mybling_remove_favorite_response(resp, form);
                   }
               });
            }
            else {
                $('bling_tooltip_action_remove_favorite_div').hide();
                var deleteLinkDiv = $('bling_tooltip_delete_link');
                var activateLinkDiv = $('bling_tooltip_activate_link');
                var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
		var polishDiv = $('bling_tooltip_action_remove_polish_div');
                if(deleteLinkDiv != null){
                        deleteLinkDiv.show();
                }
                if(activateLinkDiv != null && activateLinkDiv.readAttribute('status') != '0'){
                        activateLinkDiv.show();
                }
                removeFavoriteLinkDiv.show();
		if(polishDiv != null){
			polishDiv.show();
		}
            }

        }
        Event.stop(event);
   }
}

/*
 * AJAX response method to handle call mybling_favorite
 */

function mybling_remove_favorite_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
                        $('bling_tooltip_action_remove_favorite_div').hide();
                        $('bling_action_message').show()
                        $('bling_action_message').update(data.html);
                        removeActionMessage.delay(4, 'bling_action_message');
                }
            } else {
                var paygift_id = response.request.parameters['paygift_id'];
		if($('favorite_bling_'+paygift_id) != null){
                        $('favorite_bling_'+paygift_id).remove();
                }
		var favremdiv = $('bling_tooltip_action_remove_favorite_div');
		if(favremdiv != null){
		    favremdiv.hide();
		}
		
		var numArray = document.getElementsByClassName('bling_reorder_numbering');
		if(numArray != null){
			for (var i=0;i<numArray.length; i++){
				numArray[i].update(i+1);
			}	
		}
		hideMyblingEvent();
            }
        }
    }

}




/*
 * AJAX call to set bling as favorite
 */

function mybling_favorite(event) {
   if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            var obj = form.serialize(true);
            if(obj['m_action'] == 'Add'){

                new Ajax.Request('/a_mybling_store_action.php', {
                   parameters: form.serialize(true),
                   onSuccess: function(resp, form) {
                     mybling_favorite_response(resp, form);
                   }
               });
            }
            else {
                $('bling_tooltip_action_favorite_div').hide();
                var deleteLinkDiv = $('bling_tooltip_delete_link');
                var activateLinkDiv = $('bling_tooltip_activate_link');
                var favoriteLinkDiv = $('bling_tooltip_favorite_link');
		var polishDiv = $('bling_tooltip_action_remove_polish_div');
		if(deleteLinkDiv != null){
                	deleteLinkDiv.show();
		}
                if(activateLinkDiv != null && activateLinkDiv.readAttribute('status') != '0'){
                        activateLinkDiv.show();
                }
		if(polishDiv != null){
		    polishDiv.show();
		}
                favoriteLinkDiv.show();
            }

        }
        Event.stop(event);
   }
}

/*
 * AJAX response method to handle call mybling_favorite
 */

function mybling_favorite_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
                        $('bling_tooltip_action_favorite_div').hide();
                        $('bling_action_message').show()
                        $('bling_action_message').update(data.html);
                        removeActionMessage.delay(4, 'bling_action_message');
                }
            } else {
		
		var paygift_category = response.request.parameters['paygift_category'];
                var paygift_type = response.request.parameters['paygift_type'];
                var paygift_id = response.request.parameters['paygift_id'];
		
                $('bling_tooltip_action_favorite_div').hide();
                var deleteLinkDiv = $('bling_tooltip_delete_link');
		if(deleteLinkDiv != null && deleteLinkDiv.readAttribute('status') != '0'){
                        deleteLinkDiv.show();
                }
		var activateLinkDiv = $('bling_tooltip_activate_link');
		if(activateLinkDiv != null && activateLinkDiv.readAttribute('status') != '0'){
                	activateLinkDiv.show();
                }
		var polishDiv = $('bling_tooltip_action_remove_polish_div');
		if(polishDiv != null){
		    polishDiv.show();
		}
		var favoriteLinkDiv = $('bling_tooltip_favorite_link');
		favoriteLinkDiv.writeAttribute('status',0);
		//generateFavoriteBlingHTML(paygift_id,paygift_category,paygift_type);
		var favBlingId = $('favorite_bling_'+paygift_id);
		if(favBlingId == null){
		    $('favorite_bling_eol_marker').insert({before:data['html']});
		}
		//$('favorite_bling_eol_marker').insert({before:data['html']});
            }
        }
    }

}

function generateFavoriteBlingHTML(paygiftId, paygiftCategory, paygiftType){
	var newestCategory = '1|2|3|4|5|6';
	var normalCategory = '1|3|6|5';
	var sACategory = '2';
	var lECategory = '4';
	var paygiftHTMLId = null;
	var paygiftHTML = null;
	if(paygiftCategory != null && paygiftCategory == newestCategory){
		paygiftHTMLId = 'newest_bling_'+paygiftId;
		var paygiftInnerHTML = $(paygiftHTMLId).innerHTML;
		paygiftHTML = '<div class="bling_category_data">'+paygiftInnerHTML+'</div>';
		$('favorite_bling_eol_marker').insert({before:paygiftHTML});	
	}
	else if(paygiftCategory != null && (paygiftCategory ==normalCategory || 
			paygiftCategory == sACategory || paygiftCategory == lECategory)){
		
		paygiftHTMLId = 'bling_'+paygift_id;
		
	}
	else {
		return false;
	}
	return true;

}		

/*
 * Function to show a an element. This has been specifically written for MyBling
 */

function showBlingDeleteDiv(){
	
	var showdiv = $('bling_tooltip_action_delete_div');
	showdiv.show();

	var deleteLinkDiv = $('bling_tooltip_delete_link');
	var activateLinkDiv = $('bling_tooltip_activate_link');
	var favoriteLinkDiv = $('bling_tooltip_favorite_link');
	var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
	var polishDiv = $('bling_tooltip_action_remove_polish_div');
	if(deleteLinkDiv != null){
		deleteLinkDiv.hide();
	}
	if(activateLinkDiv != null){
		activateLinkDiv.hide();
	}
	if(favoriteLinkDiv != null){
		favoriteLinkDiv.hide();
	}
	if(removeFavoriteLinkDiv != null){
		removeFavoriteLinkDiv.hide();
	}
	if(polishDiv != null){
	    polishDiv.hide();
	}
}

function showBlingActivateDiv(){
	var showdiv = $('bling_tooltip_action_activate_div');
        showdiv.show();

        var deleteLinkDiv = $('bling_tooltip_delete_link');
        var activateLinkDiv = $('bling_tooltip_activate_link');
	var favoriteLinkDiv = $('bling_tooltip_favorite_link');
	var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
	if(deleteLinkDiv != null){
        	deleteLinkDiv.hide();
	}
	if(activateLinkDiv != null){
        	activateLinkDiv.hide();
	}
	if (favoriteLinkDiv != null){
		favoriteLinkDiv.hide();
	}
	if (removeFavoriteLinkDiv != null){
		removeFavoriteLinkDiv.hide();
	}


}

function showBlingFavoriteDiv(){

	var deleteLinkDiv = $('bling_tooltip_delete_link');
        var activateLinkDiv = $('bling_tooltip_activate_link');
	var favoriteLinkDiv = $('bling_tooltip_favorite_link');
	var polishDiv = $('bling_tooltip_action_remove_polish_div');
	if(deleteLinkDiv != null){
        	deleteLinkDiv.hide();
	}
	if(activateLinkDiv != null){
        	activateLinkDiv.hide();
	}
	if(favoriteLinkDiv != null){
		favoriteLinkDiv.hide();
	}
	if(polishDiv != null){
	    polishDiv.hide();
	}
	var showdiv = $('bling_tooltip_action_favorite_div');
        showdiv.show();
}

function showBlingRemoveFavoriteDiv(){

        var deleteLinkDiv = $('bling_tooltip_delete_link');
        var activateLinkDiv = $('bling_tooltip_activate_link');
	var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
	var polishDiv = $('bling_tooltip_action_remove_polish_div');
        if(removeFavoriteLinkDiv != null){
                removeFavoriteLinkDiv.hide();
        }
        if(deleteLinkDiv != null){
                deleteLinkDiv.hide();
        }
        if(activateLinkDiv != null){
                activateLinkDiv.hide();
        }
	if(polishDiv != null){
	    polishDiv.hide();
	}
        var showdiv = $('bling_tooltip_action_remove_favorite_div');
        showdiv.show();
}

function resize_bling_display_area(bling_div,action){
	var div = $(bling_div);
	var actionHideDiv;
	var actionShowDiv;
	
	//var dimension = div.getDimensions();
	//var width = dimension.width;

	if(action == '1'){
	    if(div != null){
	   	//div.setStyle({ height: '405px' }); 
	   	div.setStyle({ height: '405px' }); 
	    }
	    actionHideDiv = $(bling_div+"_expand");
	    actionShowDiv = $(bling_div+"_collapse");
	}
	else {
	    if(div != null){
	   	div.setStyle({ height: '105px' }); 
	    }
	    actionShowDiv = $(bling_div+"_expand");
	    actionHideDiv = $(bling_div+"_collapse");
	}
	if(actionHideDiv){
 	    actionHideDiv.hide();
	}
	if(actionShowDiv){
 	    actionShowDiv.show();
	}
}

/*
 * AJAX call to delete a user bling.
 */

function mybling_delete(event) {
    if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            var obj = form.serialize(true);
            if(obj['m_action'] == 'Delete'){
                //pageTracker._trackEvent('shmutbox_block-user', 'block');
		//var paygift_category = form['paygift_category'].getValue();
		
                new Ajax.Request('/a_mybling_store_action.php', {
                   parameters: form.serialize(true),
                   onSuccess: function(resp, form) {
                     mybling_delete_response(resp, form);
                   }
               });
            }
            else {
                 //pageTracker._trackEvent('shoutbox_block-user', 'no_block');
		$('bling_tooltip_action_delete_div').hide();
		var deleteLinkDiv = $('bling_tooltip_delete_link');
	        var activateLinkDiv = $('bling_tooltip_activate_link');
		var favoriteLinkDiv = $('bling_tooltip_favorite_link');
		var removeFavoriteLinkDiv = $('bling_tooltip_remove_favorite_link');
		var polishDiv = $('bling_tooltip_action_remove_polish_div');
        	deleteLinkDiv.show();
        	if(activateLinkDiv != null && activateLinkDiv.readAttribute('status') != '0'){
                	activateLinkDiv.show();
       	 	}
		if(favoriteLinkDiv != null && favoriteLinkDiv.readAttribute('status') != '0'){
			favoriteLinkDiv.show();
		}
		if(removeFavoriteLinkDiv != null){
			removeFavoriteLinkDiv.show();
		}
		if(polishDiv != null){
			polishDiv.show();
		}
            }
        }
        Event.stop(event);

    }
}

/*
 * AJAX response method to handle call mybling_delete
 */

function mybling_delete_response(response, form) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
		    $('bling_tooltip_action_delete_div').hide();
                    $('bling_action_message').show()
                    $('bling_action_message').update(data.html);
		    removeActionMessage.delay(4, 'bling_action_message');
                }
            } else {
		
		var hidden = response.request.parameters['paygift_id'];
                if($('bling_'+hidden) != null){
                        $('bling_'+hidden).remove();
                }
                if($('newest_bling_'+hidden) != null){
                        $('newest_bling_'+hidden).remove();
                }
		if($('favorite_bling_'+hidden) != null){
                        $('favorite_bling_'+hidden).remove();
                }


                // Decrement count for the category
                var paygift_category = response.request.parameters['paygift_category'];
                var paygift_type = response.request.parameters['paygift_type'];


                if(paygift_type == '1' || paygift_type == '3' || paygift_type == '6' || paygift_type == '5'){
                        var normalCatCount = $('normal_bling_category_count').readAttribute('count');
                        $('normal_bling_category_count').writeAttribute('count', ((normalCatCount *1)-1));
                        $('normal_bling_category_count').update('Normal:'+((normalCatCount *1)-1));
                }
                else if(paygift_type == '2'){
                        var specialAbilityCatCount = $('special_ability_bling_category_count').readAttribute('count');
                        $('special_ability_bling_category_count').writeAttribute('count', ((specialAbilityCatCount *1)-1));
                        $('special_ability_bling_category_count').update('Special Ability:'+((specialAbilityCatCount *1)-1));
                }
                else if(paygift_type == '4'){
                        var limitedEditionCatCount = $('limited_edition_bling_category_count').readAttribute('count');
                        $('limited_edition_bling_category_count').writeAttribute('count', ((limitedEditionCatCount *1)-1));
                        $('limited_edition_bling_category_count').update('Limited Edition:'+((limitedEditionCatCount *1)-1));
                }
		/*
                else if(paygift_type == '5'){
                        var bigPimpinCatCount = $('big_pimpin_bling_category_count').readAttribute('count');
                        $('big_pimpin_bling_category_count').writeAttribute('count', ((bigPimpinCatCount *1)-1));
                        $('big_pimpin_bling_category_count').update('Big Pimpin:'+((bigPimpinCatCount *1)-1));
                }
		*/
		$('bling_tooltip_action_delete_div').hide();
		var numArray = document.getElementsByClassName('bling_reorder_numbering');
		if(numArray != null){
                	for (var i=0;i<numArray.length; i++){
                        	numArray[i].update(i+1);
                	}
		}
		hideMyblingEvent();

            }
        }
    }

}


function mybling_setpref(id) 
{
    new Ajax.Request('/a_mybling_store_action.php', {
       parameters: { prefb: id },
       onSuccess: function(resp) {
            $('bling_special_ability_preference_menu').update("Saved special ability bling icon preference!");
       }
    });
}


/*
 * AJAX call to block a user. 
 */

function add_block(event) {
    if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
	    var obj = form.serialize(true);
	    if(obj['m_action'] == 'Block User!'){
		pageTracker._trackEvent('shoutbox_block-user', 'block');	
                new Ajax.Request('/a_blockuser.php', {
                   parameters: form.serialize(true),
                   onSuccess: function(resp) {
                     add_block_response(resp);
                   }
               });
	    } else {
		    pageTracker._trackEvent('shoutbox_block-user', 'no_block');
	    	    Modalbox.notification('This user is not blocked', { autoClose: 2000} );
            }
           	      
	    }
        Event.stop(event);
    } 
    Modalbox.resizeToContent();
}

/*
 * AJAX response method to handle call add_block
 */

function add_block_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
                    Modalbox.insert_error_bottom(1,data.html);
                }
            } else {
		UpdateShouts();
                Modalbox.notification('User Successfully Blocked', { autoClose: 3000} );
            }
        }
    }

}


window.location.querystring = (function() {
 
    // by Chris O'Brien, prettycode.org
 
    var collection = {};
 
    // Gets the query string, starts with '?'
 
    var querystring = window.location.search;
 
    // Empty if no query string
 
    if (!querystring) {
        return { toString: function() { return ""; } };
    }
 
    // Decode query string and remove '?'
 
    querystring = decodeURI(querystring.substring(1));
 
   // Load the key/values of the return collection
 
    var pairs = querystring.split("&");
 
    for (var i = 0; i < pairs.length; i++) {
 
        // Empty pair (e.g. ?key=val&&key2=val2)
 
        if (!pairs[i]) {
            continue;
        }
 
        // Don't use split("=") in case value has "=" in it
 
        var seperatorPosition = pairs[i].indexOf("=");
 
        if (seperatorPosition == -1) {
            collection[pairs[i]] = "";
        }
        else {
            collection[pairs[i].substring(0, seperatorPosition)] 
                = pairs[i].substr(seperatorPosition + 1);
        }
    }
 
    // toString() returns the key/value pairs concatenated
 
    collection.toString = function() {
        return "?" + querystring;
    };
 
    return collection;
})();


function getElementsByClassName(classname) {
		var node = document.getElementById("fixed_toolbar");
      		var re = new RegExp('\\b' + classname + '\\b');
      		var els = node.getElementsByTagName("*");
      		for(var i=0,j=els.length; i<j; i++) {
	      		if(re.test(els[i].className)){
				els[i].style.display= "none";
			}
		}
}

var STATUS_CHANGE = 'sc';

var event_trigger_helper = Class.create({
    events: new Hash(),

    add_event: function(type,func) {
        if (this.events.get(type) == null) {
            this.events.set(type,new Array());
        }
        this.events.get(type).push(func);
    },

    trigget_event: function(type) {
        if (this.events.get(type) != null) {
            this.events.get(type).each(function(func) { func(); });
        }
    }

});

function append_query_string_args(args) {
    var querystring = window.location.querystring;
    var tmp = querystring['stats'];
    if (tmp) {
        args.set('stats',tmp);
    }
    tmp = querystring['log_sql'];
    if (tmp) {
        args.set('log_sql',tmp);
    }
    tmp = querystring['log_memcache'];
    if (tmp) {
        args.set('log_memcache',tmp);
    }
    return args;
}



var event_helper = new event_trigger_helper();

function loadContacts(list) {
    var import_type = $("import_type").value; //only find the value once
    eval(import_type + "_loadContacts(list)");
}


var blingFavOrder = null;

function setBlingOrder(order){
	this.blingFavOrder = order;
}

function getBlingOrder(){
	return this.blingFavOrder;
}

function myblings_reorder(event) {
    $('favorite_bling_reorder_save_img_top').show();
    $('favorite_bling_reorder_save_img_bottom').show();

    if(getBlingOrder() == null){
    	$('favorite_bling_reorder_save_img_top').hide();
    	$('favorite_bling_reorder_save_img_bottom').hide();
	return;
    }
    var params = {paygift_order:getBlingOrder().toString(),action:5}; 
    new Ajax.Request('/a_mybling_store_action.php', {
        method: 'get',
        parameters: params,
        onSuccess: function(transport) {
            myblings_reorder_response(transport);
        }
    });

}

function myblings_reorder_response(response) {
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                if (!data.html.empty()) {
                }
            } else {
		        setBlingOrder(null);
            }
    	    $('favorite_bling_reorder_save_img_top').hide();
    	    $('favorite_bling_reorder_save_img_bottom').hide();
	        $('favorite_bling_reorder_save_button_bottom').addClassName('off');
	        $('favorite_bling_reorder_save_button_top').addClassName('off');
        }
    }

}

function changeSaveButtonStyleOnReorder(){
	var numArray = document.getElementsByClassName('bling_reorder_numbering');
	if(numArray != null){
    	 	for (var i=0;i<numArray.length; i++){
        		numArray[i].update(i+1);
    	 	}
	}
	$('favorite_bling_reorder_save_button_bottom').removeClassName('off');
	$('favorite_bling_reorder_save_button_top').removeClassName('off');

}

var formsubmitcounter = 0;

function singleformsubmit(buttonid) {
    if (formsubmitcounter != 0) {
        return false;
    }
    
    ++formsubmitcounter;
    $(buttonid).disable();
    return true;
}


function get_path_name() {
    var pathname = '/index';
    if (!location.pathname.empty() && location.pathname != '/') {
        pathname = location.pathname.substr(0,location.pathname.length-4);
    }
    return pathname;
}

function Comma(number) {
    number = '' + number;
    if (number.length > 3) {
        var mod = number.length % 3;
        var output = (mod > 0 ? (number.substring(0,mod)) : '');
        for (var i=0 ; i < Math.floor(number.length / 3); ++i) {
            if ((mod == 0) && (i == 0)) {
                output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
            } else {
                output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
            }
        }
        return (output);
    } else { 
        return number;
    }
}

function adminSnoopChatHistory(userid, withuserid){
    var params = {uid:userid, withuid:withuserid};
    new Ajax.Request('/a_adm_chat.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
                adminSnoopChatHistory_response(response);
            }
    });
}

function adminSnoopChatHistory_response(response){
    if(response.status == 200){
        var data = response.responseJSON;
        $('adm_chat_history').update(data.html);
    }
}

function videochat_open_request() {
	do_videochat_open_request();
}

function videochat_open_request_refresh() {
	do_videochat_open_request('refresh');
}

function do_videochat_open_request(post_click) {
    var params = {
		action: "open_request"
	};
	if (post_click != null) {
		params.post_click = post_click;
	}
    new Ajax.Request('/a_videochat_actions.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
				var div = $('videochat_open');
				if (div && response.responseJSON.html) {
					div.update(response.responseJSON.html);
				}
				var div = $('videochat_open_remove');
				if (div) {
					div.update("");
				}
				var div = $('videochat_open_request_remove');
				if (div) {
					div.update("");
				}
				if (typeof Modalbox != 'undefined') {
					Modalbox.resizeToContent();
				}
            }
    });
}

function videochat_open_already() {
	do_videochat_open_already();
}

function videochat_open_already_broadcast() {
    new Ajax.Request('/a_videochat_actions.php', {
            method: 'get',
            parameters: {action: "broadcast_request", uid: $('watch_uid').value},
            onSuccess: function(response){
	     		Modalbox.notification(response.responseJSON.html, { autoClose: 3000} );
				var div = $('videochat_open_remove');
				if (div) {
					div.update("");
				}
				var div = $('videochat_open_already_remove');
				if (div) {
					div.update("");
				}
            }
    });
}

function do_videochat_open_already() {
	var div = $('videochat_open_remove');
	if (div) {
		div.update("");
	}
	var div = $('videochat_open_already_remove');
	if (div) {
		div.update("");
	}
	if (typeof Modalbox != 'undefined') {
		Modalbox.resizeToContent();
	}
}

function videochat_open(focus) {
    var chatWindow = window.open('/videochat/index.php', 'fubarvideochat', 'width=695,height=670,menubar=no,location=no,resizable=no,scrollbars=no,status=no,left=10,top=10');
    try {
       	chatWindow.focus();
		if (!focus && focus !== null) {
        	chatWindow.blur();
			window.focus();
		}
    }
	catch (e1) {
    }
}

function hideSystemNotification(notificationid){
    var params = {nid:notificationid};
    new Ajax.Request('/a_system_feature.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
                hideSystemNotification_response(response);
            }
    });
}

function hideSystemNotification_response(response){
    if(response.status == 200){
        var data = response.responseJSON;
	if (data.error){
	    // Show message somewhere on the page	
	}
	else {
            $('system_notification').remove();
	}
    }
}
function inactivateSystemNotification(notificationid){
    var params = {action:'notification_inactivate',nid:notificationid};
    new Ajax.Request('/a_adm_system_feature.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
                inactivateSystemNotification_response(response, notificationid);
            }
    });
}
function inactivateSystemNotification_response(response, nid){
    if(response.status == 200){
        var data = response.responseJSON;
	if (data.error){
	    // Show message somewhere on the page	
	}
	else {
	    var active_id = $('active_notification_'+nid);
	    if(active_id != null){
                active_id.remove();
            }
	    var inactive_to_active_id = $('active_notification_made_inactive_'+nid);
	    if(inactive_to_active_id != null){
            	inactive_to_active_id.show();
	    }
	    var new_notification = $('adm_notification_new');
	    if(new_notification != null){
		new_notification.show();
	    }
	}
    }
}

function add_new_notification(formid){

    var tmp = $(formid).serialize(true);
    new Ajax.Request("/a_adm_system_feature.php", {
            method: 'post',
            parameters: tmp,
            onSuccess: function(response) {
                add_new_notification_response(response);
            }
    });
}

function add_new_notification_response(response){
    if(response.status == 200){
        var data = response.responseJSON;
        if (data.error){
	}
	else {
	    var new_notification = $('adm_notification_new');
            if(new_notification != null){
                new_notification.remove();
            }
	    var new_notification_success = $('adm_notification_new_success');
            if(new_notification_success != null){
                new_notification_success.show();
            }
	}
    }
}

function remove_referrer(event) {
	
    if (!event.stopped) {
        var form = $(Event.element(event));
        if (form) {
            var obj = form.serialize(true);
                new Ajax.Request('/a_remove_referrer.php', {
                   parameters: form.serialize(true),
                   onSuccess: function(resp) {
                     remove_referrer_response(resp);
                   }
               });

        }
        Event.stop(event);
    }
    Modalbox.resizeToContent();
}

function remove_referrer_response(response){
    if(response.status == 200){
	var data = response.responseJSON;
        if (data.error){
	    $('remove_referrer_err_msg').update(data.html);
	    $('remove_referrer_err_msg').show();
        }
        else {
	     $('remove_referrer_err_msg').update(data.html);
             $('remove_referrer_err_msg').hide();
             $('remove_referrer_profile').remove();
	     Modalbox.notification('Referrer sucessfully removed', { autoClose: 3000} );
    	     Modalbox.resizeToContent();
	
        }
    }
}

function mybling_polish(formid){

    var params = $(formid).serialize(true);
    new Ajax.Request('/a_mybling_store_action.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
                mybling_polish_response(response);
            }
    });
}

function mybling_polish_response(response){

    var paygift_id = response.request.parameters['paygift_id'];
    var paygift_category = response.request.parameters['paygift_category'];
    var paygift_type = response.request.parameters['paygift_type'];	
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                 $('bling_action_message').show()
                 $('bling_action_message').update(data.html);
                 removeActionMessage.delay(4, 'bling_action_message');
	    }
	    else {
		$('overlay_'+paygift_id+'_tooltip').remove();
		$('bling_'+paygift_id+'_tooltip_img').writeAttribute('style','');
		$('bling_tooltip_action_remove_polish_div').remove();
		/*var newest_bling = $('newest_bling_'+paygift_id);
		if(newest_bling != null){
		    newest_bling.update(data.html);
		}
		var reg_bling = $('bling_'+paygift_id);
		if(reg_bling != null){
		    reg_bling.update(data.html);
		}
		
		var fav_bling = $('favorite_bling_'+paygift_id);
                if(fav_bling != null){
                    reg_bling.update(data.html);
                }*/

		// Overlay for Newest, Normal and Fav
		var overlay_new = $('overlay_newest_'+paygift_id);
		var overlay_reg = $('overlay_'+paygift_id);
		var overlay_fav = $('overlay_favorite_'+paygift_id);

		if(overlay_new != null){
		    overlay_new.remove();
		}
		if(overlay_reg != null){
		    overlay_reg.remove();
		}
		if(overlay_fav != null){
		    overlay_fav.remove();
		}

		// Image for Newest, Normal and Fav
		var img_new = $('newest_bling_'+paygift_id+'_img');
		var img_reg = $('bling_'+paygift_id+'_img');
		var img_fav = $('favorite_bling_'+paygift_id+'_img');

		if(img_new != null){
		    img_new.writeAttribute('style','');
		}
		if(img_reg != null){
		    img_reg.writeAttribute('style','');
		}
		if(img_fav != null){
		    img_fav.writeAttribute('style','');
		}

		// This is for the user profile page
		var overlay_profile = $('overlay_'+paygift_id);
		if(overlay_profile != null){
			overlay_profile.remove();
		}
		var msg = 'You were awarded '+data.html+ ' points';
		$('bling_action_message').show()
                $('bling_action_message').update(msg);
		removeActionMessage.delay(5, 'bling_action_message');

	    }
    	}
    }
}

var OverlayWatcherClass = Class.create({
    initialize: function(divid1,divid2) {
        this.bind_mouseover = this.mouseover.bind(this);
        this.bind_mouseout = this.mouseout.bind(this);
        this.bind_timer = this.timer.bind(this);
 
        this.timer = 0;
   
        this.div1 = $(divid1);
        this.div1.observe('mouseover',this.bind_mouseover);
        this.div1.observe('mouseout',this.bind_mouseout);
 
        this.div2 = $(divid2);
        this.div2.observe('mouseover',this.bind_mouseover);
        this.div2.observe('mouseout',this.bind_mouseout);
    },
 
    cleanup: function() {
        this.stoptimer();
 
        if (this.div1) {
            this.div1.stopObserving('mouseover',this.bind_mouseover);
            this.div1.stopObserving('mouseout',this.bind_mouseout);
            this.div1 = null;
        }
        if (this.div2) {
            this.div2.stopObserving('mouseover',this.bind_mouseover);
            this.div2.stopObserving('mouseout',this.bind_mouseout);
            this.div2 = null;
        }
    },
 
    stoptimer: function() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = 0;
        }
    },
 
    starttimer: function() {
        this.stoptimer();
        this.timer = setTimeout(this.bind_timer,500);
    },
   
    mouseover: function(event) {
        this.stoptimer();
    },
 
    mouseout: function(event) {
        this.starttimer();
    },
 
    timer: function(event) {
        if (this.div2) {
            this.div2.hide();
        }
 
        this.cleanup();
    }
 }
);

function submit_cca(result,formid){
    if (result) {
        var params = $(formid).serialize(true);
        new Ajax.Request('/a_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               submit_cca_response(response);
            }
        });
    }
    return false;
}

function submit_cca_response(response){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                 $('ccaerrmsg').show();
                 $('ccaerrmsg').update(data.html);
	        } else if (data.errors) {
                for (var i=0; i<data.errors.length; ++i) {
                    var error = data.errors[i];
                    ccavalidation.drawFail('other', error.field, error.error);
                 }
            } else {
                $('ccaerrmsg').hide();
	   	        $('cca_show').hide(); 
		        $('ccasuccessmsg').show();
	        }
	    }
    }
}

function approve_cca(uid){
    var params = {action:'approvecca',ccauid:uid};
    new Ajax.Request('/a_adm_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               approve_cca_response(response,uid);
            }
    });
}

function approve_cca_response(response,uid){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
		var err = $('cca_action_err');
		if(err){
	            err.show();
		    err.update(data.html);
	    	}
	    }	
            else {
                $(uid+'_cca_user_approve').update("Approved");
                $(uid+'_cca_user_blocked').update("Approved");
                $(uid+'_cca_user_reminder').update("Approved");
	    }
        }
    }
}

function send_cca(uid){
    var params = {action:'sendcca',ccauid:uid};
    new Ajax.Request('/a_adm_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               send_cca_response(response,uid);
            }
    });
}

function send_cca_response(response,uid){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                $('adm_cca_send_link').hide();
                $('adm_cca_sent').show();
		$('adm_cca_sent').update(data.html);
            }
            else {
                $('adm_cca_send_link').hide();
                $('adm_cca_sent').show();
            }
        }
    }
}


function block_cca(uid){
    var params = {action:'blockcca',ccauid:uid};
    new Ajax.Request('/a_adm_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               block_cca_response(response,uid);
            }
    });
}

function block_cca_response(response,uid){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                var err = $('cca_action_err');
                if(err){
                    err.show();
                    err.update(data.html);
                }
            }
            else {
		var err = $('cca_action_err');
		if(err){
		   err.hide();
		}
                $(uid+'_blockcca').hide();
                $(uid+'_unblockcca').show();
            }
        }
    }
}

function unblock_cca(uid){
    var params = {action:'unblockcca',ccauid:uid};
    new Ajax.Request('/a_adm_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               unblock_cca_response(response,uid);
            }
    });
}

function unblock_cca_response(response,uid){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                var err = $('cca_action_err');
                if(err){
                    err.show();
                    err.update(data.html);
                }
            }
            else {
		var err = $('cca_action_err');
                if(err){
                   err.update("");
                }
                $(uid+'_unblockcca').hide();
                $(uid+'_blockcca').show();
            }
        }
    }
}
function view_cca(uid){
    
	window.open ("http://"+document.location.hostname+"/adm_cca.php?action=viewcca&ccauid="+uid,"mywindow","menubar=1,resizable=1,width=600,height=700");

}

function view_cca_response(response,uid){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
		 var err = $('cca_action_err');
                if(err){
                    err.show();
                    err.update(data.html);
                }
	    }
            else {
            	$('parent_adm_cca_div').update(data.html);
            }
        }
    }
}

function view_reject_cca(uid){
    window.open ("http://"+document.location.hostname+"/adm_cca.php?action=viewrejectcca&ccauid="+uid,"mywindow","menubar=1,resizable=1,width=600,height=400");
}

function reject_cca(formid){
    var params = $(formid).serialize(true);
    new Ajax.Request('/a_adm_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               reject_cca_response(response);
            }
    });
}

function reject_cca_response(response){
    var uid = response.request.parameters['ccauid'];
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                var err = $('cca_reject_msg');
                if(err){
                    err.show();
                    err.update(data.html);
                }
            }
            else {
                var err = $('cca_reject_msg');
                if(err){
                   err.update("Rejected");
                }
		var reject=$(uid+'_rejected');
		if(reject){
			reject.hide();
		}
		var already_reject=$(uid+'_already_rejected');
		if(already_reject){
			already_reject.show();
		}
            }
        }
    }
}

function reminder_cca(uid){
    var params = {action:'remindercca',ccauid:uid};
    
    new Ajax.Request('/a_adm_cca.php', {
            method: 'get',
            parameters: params,
            onSuccess: function(response){
               reminder_cca_response(response,uid);
            }
    });
}

function reminder_cca_response(response,uid){
    if (response.status == 200) {
        var data = response.responseJSON;
        if (data) {
            if (data.error){
                var err = $('cca_action_err');
                if(err){
                    err.show();
                    err.update(data.html);
                }
            }
            else {
                var err = $('cca_action_err');
                if(err){
                   err.update("");
                }
                $(uid+'_cca_user_reminder').update("Notification Sent");
            }
        }
    }
}

function sort_cca(action,sortid){
	window.location="http://"+document.location.hostname+"/adm_cca.php?action="+action+"&sort="+sortid;
}

function login_points_lightbox () {
    var box = '/lb_login_points.php';
    lightboxActive();
    open_lightbox_manual(box);
}

// this checks for validation script to be loaded, if its not load dynamically
var global_modalvalidatorholder = undefined;
function load_verification(callback) {
    if (typeof global_modalvalidatorloaded  == "undefined") {
		var script = new Element("script", { type: "text/javascript", src: "/js/validation.js" });
		document.observe("validation:loaded", function() { global_modalvalidatorholder = new modalvalidatorholder(); });
		$$("head")[0].insert(script);
		if (callback) {
			document.observe('validation:loaded', callback);
		}
	}
	else {
		if (global_modalvalidatorholder == null) {
			global_modalvalidatorholder = new modalvalidatorholder()
		}
		if (callback) {
			callback();
		}
	}
}

// this checks for swfobject script to be loaded, if its not load dynamically
var swfobject = undefined;
function load_swfobject(callback) {
    if (typeof swfobject == "undefined") {
		var script = new Element("script", { type: "text/javascript", src: "/js/swfobject.js" });
		$$("head")[0].insert(script);
		if (callback) {
			document.observe('swfobject:loaded', callback);
		}
	}
	else {
		if (callback) {
			callback();
		}
	}
}

function hide_header(){
		var el=$('header_control');
		$('middle_header_panel').hide();	
		$('msgticker_wrapper').hide();
		$('notifications_container').show();

 		var buttons = $$('a.collapse');
		for (var i = 0; i < buttons.length; ++i) {
			buttons[i].removeClassName('collapse');
			buttons[i].addClassName('expand');
		}
		
	}

function show_header() {
		var el=$('header_control');
		$('notifications_container').hide();
		$('middle_header_panel').show();
		$('msgticker_wrapper').show();
		var buttons = $$('a.expand');
		for (var i = 0; i < buttons.length; ++i) {
			buttons[i].removeClassName('expand');
			buttons[i].addClassName('collapse');
		}
}

function toggle_header(){	
	if ($('middle_header_panel').visible()){
		hide_header();
	}else{
		show_header();		
	}
}

Number.prototype.unsign = function(bytes) {
  return this >= 0 ? this : Math.pow(256, bytes || 4) + this;
};

function crc16(data) {
  var CRC=0xffffffff;
  data = data.toLowerCase();
  for (var j=0; j<data.length; j++) {
    var c = data.charCodeAt(j);
    CRC ^= c << 24;
    for(var i = 0; i<8; i++) {
        if(CRC.unsign(8) & 0x80000000) {
          CRC = (CRC << 1) ^ 0x04C11DB7;
        } else{
          CRC <<= 1;
        }
     }
  }
  if ( CRC < 0 ) CRC = CRC>>>0;
  return CRC.toString(16);
}
