<!--
var win;
var xmlHttp;

timedouturl = "index";

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

function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

function send_email(p,new_win){
	if (new_win=='new'){
		window.open('send_email?'+p);
	}else{
		window.location.href='send_email?'+p;
	}
}

function clickOnce(){
	clickOnceForm(document.update.submitbut);
}

function clickOnceForm(f){
    f.value='Please wait...';
    f.disabled=true;
}

function checkPopup(){
    if (!(win && win.open && !win.closed)) {
        var text = "Please enable popups on our site!";
        var html = "<P align=justify class=main_text_l><b>" + text + "</b></p>";
        //if (document.all && document.all.warning)
           // document.all.warning.innerHTML = html;
        //else if (document.getElementById('warning'))
          //  document.getElementById('warning').innerHTML = html;
    }
}

function PopUpEx(sendLink, name, width, height, scrollbars) {
    mm= "width=" + width + ",height=" + height + ",scrollbars=" + scrollbars;
    win = window.open(sendLink, name, mm);
    if (win && win.open && !win.closed)
        win.focus();
    return win;
}

function PopUp(sendLink, name, width, height, scrollbars) {
    PopUpEx(sendLink, name, width, height, scrollbars);
}

function newwindow(a,windowname, width, height, scrollbars, process_link){
    var mm= "width=" + width + ",height=" + height + ",scrollbars=" + scrollbars + ",resizable=" + scrollbars;
    var url = a.href;
    var win = window.open(a.href, windowname, mm);
    if (win && win.open && !win.closed){
        win.focus();
    }
    if(process_link == null){
    	process_link = false;
    }
   return process_link;
}

function confirmwindow(c_text,c_url,win_name,width,heigh,scrollbars) {
    if (confirm(c_text)){
		PopUpEx(c_url,win_name,width,heigh,scrollbars);
	}
}

function disp_confirm()
{
    if(confirm('Are you sure you want to remove this email from invite history?'))
    {
        return true;
    }else{
        return false;
    }
}

function blog_del_confirm(info)
{
    var hint = info;
    if(confirm(hint))
    {
        return true;
    }else{
        return false;
    }
}

function modelesswin(url,mwidth,mheight,winname){
    if (document.all&&window.print){ 
        eval('window.showModelessDialog(url,winname,"help:0;resizable:1;dialogWidth:'+mwidth+'px;dialogHeight:'+mheight+'px")');
    }else{
        eval('window.open(url,winname,"width='+mwidth+'px,height='+mheight+'px,resizable=1,scrollbars=1")');
    }   
}

function fixForm(c)
{
  var i;
  var n = c.name;
  var l = c.form.elements.length;
  if (!c.checked) return;
  if (c.value == '0') {
    for (i = 0 ; i < l ; i++){
      var e = c.form.elements[i];
      if(e.name == n && e.value != c.value) e.checked=false;
    }
  } else {
    for (i = 0 ; i < l ; i++){
      var e = c.form.elements[i];
      if(e.name == n && e.value == '0') e.checked=false;
    }

  }
  return;
}

function CheckPassLenght(c)
{
	var s = c.value.indexOf(" ");
	document.getElementById('view').innerText='(Minimum 4 characters for security reasons. No spaces or special characters.)'; 
	document.getElementById('view').style.color='#000000';
	document.getElementById('view').style.fontWeight = '';
	var format = /\D\W/;
	var result;
	result = c.value.match(format);
if (result) { 
    document.getElementById('view').innerText='[Enter password again. You cannot include special characters in your passwords.]'; 
	document.getElementById('view').style.color='#FF0000';
	document.getElementById('view').style.fontWeight = 'bold';
	document.getElementById('password').value= '';
    document.getElementById('password').focus();
}else{
	if (s>=0){
		document.getElementById('view').innerText='[Enter password again. You cannot include any space in your password!]';
		document.getElementById('view').style.color='#FF0000';
		document.getElementById('view').style.fontWeight = 'bold';
		document.getElementById('password').value='';
		document.getElementById('password').focus();
	}
	if(c.value.length != 0) {
		if( (c.value.length < 4) || (c.value.length > 12) ) {
			document.getElementById('view').innerText='[Your password must contain between 4 and 12 characters.No spaces or special characters.]';
			document.getElementById('view').style.color='#FF0000';
			document.getElementById('view').style.fontWeight = 'bold';
			document.getElementById('password').value='';
			document.getElementById('password').focus();
		}
	}
}
}
 
function popUpPayment(){
    PopUp('pay','pay',800,700, 'yes');
}

function im_guest_notice(fname){
    PopUp('im_guest_notic.htm?fname='+fname,'im_guest_notic',437,320, 'yes');
}

function goldMemberOnly(message1,message2,message3)
{
   var mes;
   if ((message1==null) && (message2==null) && (message3==null)){
      mes="This service is for gold members only. By becoming a gold member, you can access all services without restriction.";
   } else {
      if (message3!=""){
        mes=message3;
      }else{
        mes=message1;
        mes+= message2;
      }
   }
   modelesswin('goldMemberOnlyMessage_?message='+mes,440,486,'paymessage');
}

function goldMemberOnlyChat(party_id, party_name)
{
  goldMemberOnly(null,null,null);
}

function subscribe_today(message1,message2,message3)
{
   var mes;
   if ((message1==null) && (message2==null) && (message3==null)){
      mes="This service is for gold members only. By becoming a gold member, you can access all services without restriction.";
   } else {
      if (message3!=""){
        mes=message3;
      }else{
        mes=message1;
        mes+= message2;
      }
   }
   modelesswin('_subscribe_today?message='+mes,420,486,'paymessage');
}

function checkFrame(site) {
	try {
    var isFrame= self.parent.frames.length;
    if (isFrame==0){
        url=document.location;
        var re1 = /search_results/;
        if (re1.test(url)==true) {
            new_location = 'http://www.' + site + '/index.html?url=';
            try {
                        new_location += encodeURIComponent(url);
            } catch (e) {
                        new_location += escape(url);
            }
            document.location = new_location;
       }
    }
	} catch (e) {}
}

function RevealProfile(nextPage) {
    var newHref = "set_hidden?hide=0";
    if(nextPage!=null)
      newHref+="&next="+nextPage;
    window.location.href = newHref;
}

function HideProfile() {
    if (confirm('You can still use all the features.  But others will not be able to see your profile.\nAre you sure you want to hide the profile?'))
        window.location.href = "set_hidden?hide=1";
}

function profileIncomplete(){
     alert("Please complete your registration to use our services!");
     //window.location.href = "my_profile";
}

function countLineBreaks (string) {
    var re = /\r\n|\r|\n/g;
    var n = 0;
    while (re.exec(string))
        n++;
    return n;
}

/* if needed, tries to increase the number of rows of a textarea */
function growTAVert (textarea) {
    var lineBreaks = countLineBreaks(textarea.value);
    if (textarea.rows * textarea.cols < textarea.value.length) {
        var newRows = lineBreaks +
                      parseInt(textarea.value.length / textarea.cols) + 2;
        newRows = newRows <= 40 ? newRows : 40;
        textarea.rows = newRows;
    } else if (textarea.rows < lineBreaks) {
        textarea.rows = lineBreaks + 2;
    }
}

function mc (id) {
    var obj = eval("document.forms.accounts.changed_" + id);
    obj.value = 1;
}

try{
     if (window.parent.document.title){
    window.parent.document.title=window.self.document.title;
     }
}catch(e){}


function checklogin()
{
     return get_XML_data("_check_authen");
}

function get_XML_data(data_url)
{
     var strResult=0;
	 var ua = navigator.userAgent;
	 if(ua.indexOf('Mac') > -1 && ua.indexOf('AOL') > -1) strResult = 1;
     else {
        if (document.getElementById){
             try{
               strResult = NetScapeShow(data_url);
             }catch(e){
               strResult = IEShow(data_url);
             }
         }else{
              strResult = IEShow(data_url);
         }
     }
     return strResult;
}
 
function NetScapeShow(data_url){
 xmlHttp = new XMLHttpRequest();
 xmlHttp.open("GET", data_url, false);
 xmlHttp.send(null);
 xmlDoc = xmlHttp.responseText;
 var strResult =xmlDoc;
 return strResult;
}
 
function IEShow(data_url){
 var oBao = new ActiveXObject("Microsoft.XMLHTTP");
 oBao.open("GET",data_url,false);
 oBao.send();
 var strResult = unescape(oBao.responseText);
 return strResult;
}

function syncForm(){
    var strResult=0;
    strResult = checklogin();
    if (!strResult){
        alert("Sorry, your session has expired. \nPlease log on again after copy your composing to your notepad!");
        return false;
    }else{
	return true;
    }
}

function setSelectValue(sel,val){
  var i;
  for (i=0;i<sel.length;i++) {
    if (sel.options[i].value == val){
      sel.selectedIndex = i;
    }
  }	     
}

function FullSize(url,ix,iy) {
    if(ix>0) {
        PopUp(url,"fsphoto",ix+6,iy+6,"no");
    }
}

function setPhotoAbout(id){
  PopUp('_set_picabout?id='+id,"about",435,388,"no");

}



function getFormFieldValue(field) {
    switch (field.type) {

        case "button" :
        case "file" :
        case "hidden" :
        case "password" :
        case "reset" :
        case "submit" :
        case "text" :
        case "textarea" :
            return field.value;

        case "select-one" :
            var i = field.selectedIndex;
            if (i == -1)
                return "";
            else
                return (field.options[i].value == "") ? field.options[i].text : field.options[i].value;

        case "select-multiple" :
            var result = new Array();
            for (var i = 0; i < field.options.length; i++)
                if (field.options[i].selected)
                    result[result.length] = (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
            return result;

        case "radio" :
        case "checkbox" :
            if (field.checked)
                return field.value;
            else
                return "";

        default :
            if (field[0].type == "radio") {
                for (i = 0; i < field.length; i++)
                    if (field[i].checked)
                        return field[i].value;

                return "";
            } else if (field[0].type == "checkbox") {
                var result = new Array();
                for (i = 0; i < field.length; i++)
                    if (field[i].checked)
                        result[result.length] = field[i].value;

                return result;
            } else {
                // unknown field type
            }
            break;
    }
   
    return "";
}

function fixPiclist(obj, usr_id, picno) {
    var form = obj.form;
    var npics = form.elements['npics__' + usr_id].value;
    var makemain = form.elements['makemain__' + usr_id];
    var picno_main = npics > 1 ? getFormFieldValue(makemain) : 0;
    if (picno_main == "") picno_main = -1;

    // clear the other rank
    if (obj.name.substr(0, 6) == 'rank__' && obj.checked == 1)
        form.elements['rank4__' + usr_id].checked = 0;
    if (obj.name.substr(0, 7) == 'rank4__' && obj.checked == 1)
        form.elements['rank__' + usr_id].checked = 0;

    // undelete the main photo if setting a rank
    if ((obj.name.substr(0, 6) == 'rank__' ||
         obj.name.substr(0, 7) == 'rank4__') && obj.checked == 1)
    {
        // if there is no main photo, then use first pic for main photo
        if (picno_main == -1) {
            picno_main = 0;
            if (npics > 1) {
                makemain.value = picno_main = 0;
                makemain[0].checked = 1;
            }
        }

        form.elements['delp__' + usr_id + '_' + picno_main].checked = 0;
    }

    // "undelete" the main photo
    if (obj.name.substr(0, 10) == 'makemain__' && picno == picno_main) {
        form.elements['delp__' + usr_id + '_' + picno].checked = 0;
    }

    if (obj.name.substr(0, 6) == 'delp__' && obj.checked == 1) {
        if (picno == 0 && npics == 1) {
            // set rank to 0
            form.elements['rank__' + usr_id].checked = 0;
            form.elements['rank4__' + usr_id].checked = 0;
        } else {
            // if pic to be deleted is the main photo,
            // then use the first not deleted pic for main photo
            if (picno == picno_main) {
                for (var i = 0; i < npics; i++) {
                     if (form.elements['delp__' + usr_id + '_' + i].checked == 0) {
                         makemain.value = picno_main = i;
                         makemain[i].checked = 1;
                         break;
                     }
                }
            }

            // if all pics will be deleted, set rank to 0
            if (i == npics) {
                form.elements['rank__' + usr_id].checked = 0;
                form.elements['rank4__' + usr_id].checked = 0;
                makemain[picno_main].checked = 0;
                makemain.value = picno_main = -1;
            }
        }
    }
}

function RotateImg(obj, usr_id, picno, nocensor) {
    var angle = 0;
    var uid = usr_id + '_' + picno;
    angle = parseInt(document.getElementById("rangle__"+uid).value) + parseInt(obj.name);
    var rotation = 0;
    if(Math.abs(angle) >= 360)
        if(angle > 0) angle -= 360;  
        else angle += 360;  
    document.getElementById("rangle__"+uid).value = angle;
    //only for IE v.5.5 and above 
    if(navigator.appName=="Microsoft Internet Explorer"){
        if(angle < 0) angle += 360;
        switch (angle){
            case  90 : rotation = 3; break;
            case 180 : rotation = 2; break;
            case 270 : rotation = 1; break;
        }
        document.getElementById("photo__"+uid).style.filter = "progid:DXImageTransform.Microsoft.BasicImage(rotation="+rotation+")";
    } else {
        var url = "show_rotated_img_?usr_id=" + usr_id + "&picno=" + picno + "&angle=" + angle;
        if (nocensor) url += '&nocensor=1';
        document.getElementById("photo__" + uid).src = url;
    }
}

function RotateImgWithoutDB(obj, usr_id, picno, item_id) {
    var angle = 0;
    var uid = usr_id + '_' + picno + '_' + item_id;
    angle = parseInt(document.getElementById("rangle__"+uid).value) + parseInt(obj.name);
    var rotation = 0;
    if(Math.abs(angle) >= 360)
        if(angle > 0) angle -= 360;  
        else angle += 360;  
    document.getElementById("rangle__"+uid).value = angle;
    //only for IE v.5.5 and above 
    if(navigator.appName=="Microsoft Internet Explorer"){
        if(angle < 0) angle += 360;
        switch (angle){
            case  90 : rotation = 3; break;
            case 180 : rotation = 2; break;
            case 270 : rotation = 1; break;
        }
        document.getElementById("photo__"+uid).style.filter = "progid:DXImageTransform.Microsoft.BasicImage(rotation="+rotation+")";
    } else {
        var url = "show_rotated_img_without_db_?usr_id=" + usr_id + "&picno=" + picno+ "&item_id=" + item_id + "&angle=" + angle;
        document.getElementById("photo__" + uid).src = url;
    }
}

function OnLoadPage(site) {
}

function clickSearchOnce(){
    var html="<center><br><input type='submit' value='Please wait...' disabled></center>";
    if (document.getElementById('showsearch')) {
        document.getElementById('showsearch').innerHTML = html;
    } else if (document.all && document.all.showsearch) {
        document.all.showsearch.innerHTML = html;
    }
	return true;
}

function clickContinueOnce() {
    var html="<input type='submit' value='Please wait...' disabled>";
    if (document.check.showcontinue){
            document.check.showcontinue.innerHTML = html;
    }else if (document.getElementById('showcontinue')){
            document.getElementById('showcontinue').innerHTML = html;
    }
	return true;
}
function set_start_height(oForm, startValue) {
	var fOption = oForm.options;
        if(!fOption[0].selected == true) {
        	return;
        }   
 	for (var i = 0; i < fOption.length; i++)
        if (fOption[i].value == startValue) fOption[i].selected = true;
}

function setRadioValue(f, name, value){
  var i;
  var l = f.elements.length;
  for (i = 0 ; i < l ; i++){
      var e = f.elements[i];
      if(e.name == name){
            e.checked = (e.value == value? true: false);
      } 
  }
}
function show_hide_dist(r) {
	try{
		var r_value = r.value;
		if (r.name != 'is_distance'){
			if (r.name.indexOf('_cou')!= -1 || r.name.indexOf('state')!= -1){ // is country
				r_value = 0;
			}else{
				r_value = 1;
			}
			setRadioValue(r.form, 'is_distance', r_value);   
		}
	} catch (e) {}
}
function checkMessages(theBox,theArray) {
		if ( theBox.checked ) {
			for (i = 0; i < theArray.elements.length; i++) {
				try{
					theArray.elements[i].checked = true ;
				}catch(e){}
			}
			theBox.form.checkall.checked = true;
		} else {
			for (i = 0; i < theArray.elements.length; i++) {
				try{
					theArray.elements[i].checked = false ;
				}catch(e){}
			}
			theBox.form.checkall.checked = false;
		}
}
function checkForm(frm){
	var sel = false;
	if(frm.del.length){
		for(var i=0;i<frm.del.length;i++){ 
			if(frm.del[i].checked){
				sel = true;
				break;
			}
		}
	}
	else{
		sel = frm.del.checked;
	}
	if(!sel){
		document.getElementById("error_div").style.display = 'block';
		document.location ='#top';
		return false;
	}
	return true;
}
function registerAlert() {
    alert('Please register to use the feature');
}


function createHiddenFormElement(inputForm, elementName, elementValue){
    var newElement = document.createElement("INPUT");
    newElement.type = "HIDDEN";
    newElement.name = elementName;
    newElement.value = elementValue;
    return inputForm.appendChild(newElement);
}

var submitForm, c_form_name, c_formtag, c_text;

function check_spell_open(form_text_tag,form_name){
    if (!form_name) form_name ='update';
    var text = document.getElementById(form_text_tag).value;

    if(text.length < 1000) {
      return PopUpEx('/spell_checker_?form_name='+form_name+'&form_text_tag='+form_text_tag+'&text='+escape(text),'check_spell',500,400,'yes');
    } 

    PopUpEx('about:blank','check_spell',500,400,'yes');

    if(typeof(submitForm) == 'undefined') {
        submitForm = document.createElement("FORM");
        document.body.appendChild(submitForm);
        c_form_name = createHiddenFormElement(submitForm, "form_name", form_name);
        c_formtag = createHiddenFormElement(submitForm, "form_text_tag", form_text_tag);
        c_text=  createHiddenFormElement(submitForm, "text", text);
    } else {
        c_form_name.value = form_name;
        c_formtag.value = form_text_tag;
        c_text.value = text;
    }
    submitForm.method = "POST";
    submitForm.target = 'check_spell';
    submitForm.action= "/spell_checker_";
    submitForm.submit();
}

function check_spell(form_text_tag,form_name){
      if (!form_name) form_name ='update';
      var text = document.getElementById(form_text_tag).value;
      var reg = /\bblog\b|\bblogs\b|\bblogging\b|\bblogland\b|\bbloggers\b/gi;
      text = text.replace(reg,"")

      jQuery.ajax({
          type: "POST",
          url: "/_check_spell",
          data: { 
              form_name: form_name, form_text_tag: form_text_tag, text: escape(text), ajaxRequestUncache: parseInt(Math.random() * 1000000) 
          },
          success: function(info){
             if(info=='1'){
                alert("No misspelling found!");
             }else{
                check_spell_open(form_text_tag,form_name);
             }
          }
      });
}


// utility function to retrieve an expiration date in proper

// format; pass three integer parameters for the number of days, hours,

// and minutes from now you want the cookie to expire (or negative

// values for a past date); all three parameters are required,

// so use zeros where appropriate

function getExpDate(days, hours, minutes) {

    var expDate = new Date( );

    if (typeof days == "number" && typeof hours == "number" && 

        typeof hours == "number") {

        expDate.setDate(expDate.getDate( ) + parseInt(days));

        expDate.setHours(expDate.getHours( ) + parseInt(hours));

        expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));

        return expDate.toGMTString( );

    }

}

// utility function called by getCookie( )

function getCookieVal(offset) {

    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1) {

        endstr = document.cookie.length;

    }

    return unescape(document.cookie.substring(offset, endstr));

}

// primary function to retrieve cookie by name

function getCookie(name) {

    var arg = name + "=";

    var alen = arg.length;

    var clen = document.cookie.length;

    var i = 0;

    while (i < clen) {

        var j = i + alen;

        if (document.cookie.substring(i, j) == arg) {

            return getCookieVal(j);

        }

        i = document.cookie.indexOf(" ", i) + 1;

        if (i == 0) break; 

    }

    return "";

}

// store cookie value with optional details as needed

function setCookie(name, value, expires, path, domain, secure) {

    document.cookie = name + "=" + escape (value) +

        ((expires) ? "; expires=" + expires : "") +

        ((path) ? "; path=" + path : "") +

        ((domain) ? "; domain=" + domain : "") +

        ((secure) ? "; secure" : "");

}

// remove the cookie by setting ancient expiration date

function deleteCookie(name,path,domain) {

    if (getCookie(name)) {

        document.cookie = name + "=" +

            ((path) ? "; path=" + path : "") +

            ((domain) ? "; domain=" + domain : "") +

            "; expires=Thu, 01-Jan-70 00:00:01 GMT";

    }

}



//Instant Messenger functions

var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
var chats = new Array();
var CommandBlocked = false;

function startIM (usr_id) {
   PopUp("http://www.PositiveSingles.com/im_users_list.htm","im_" + usr_id,370,500,"no, resizable=1");
}

function startPrivateChat(partyname, username) {
	var im_usersObj = isInternetExplorer ? document.all.im_users : document.im_users;
    var param = 'partyname=' + partyname;
	if((chats[partyname]==null) || (typeof(chats[partyname])=="undefined") || (chats[partyname].closed)) {
		try {
			chats[partyname] = PopUpEx('http://www.PositiveSingles.com/im_private.htm?' + param, 'MIM_to_' + partyname, 500, 330, 'no, resizable=1');
		} catch(e) { alert("error:" + e)};
		if(chats[partyname]==null || typeof(chats[partyname])=="undefined") {
//TODO: Possible, popups is blocked. Display notification.
			if(im_usersObj) {
				im_usersObj.TGotoLabel("/", "PopupBlocked");
			}
		}
	} else {
//TODO: Add blinking effect to window chats[partyname]. Don't know how to do it...
	}
}

// add to bookmark
function addBookmark() 
{
	if (window.sidebar) 
	{
		window.sidebar.addPanel(document.title, document.location.href,"");
	} 
	else if(document.all) 
	{
		window.external.AddFavorite( document.location.href, document.title);
	} 
	else if( window.opera && window.print )
	{
	return true;
	}
} 

function selectAllWithTextarea(textarea) {
    try {
        textarea.focus();
        textarea.select();
    } catch (e) {
//        alert(e);
    }
}

function getXMLHttpRequest()
{
	var http_request;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
		return http_request;

}

function popupMsg(id){
       document.getElementById(id).style.display='';
}
function hiddenMsg(id){
       document.getElementById(id).style.display='none';
}

function HideandUNhideObj(i){
        nav=document.getElementById('div'+i).style;
        con=document.getElementById('ul'+i);
        if(nav.display=="none"){
                // set mouseout function here
                nav.display = 'block';
                con.onmouseout = function(evt) {
                    if (checkMouseLeave(this, evt)) {
                        i = parseInt(this.id.substr(2));
                        nav=document.getElementById('div'+i).style;
                        nav.display = 'none';
                    }
                }
        } else {
                nav.display='none';
                con.onmouseout = function (evt) {
                    if (checkMouseLeave(this, evt)) {
                        i = parseInt(this.id.substr(2));
                        nav=document.getElementById('div'+i).style;
                        nav.display= 'none';
                    }
                }
        }
}

function checkMouseLeave (element, evt) {

  evt = (evt) ? evt : ((window.event) ? window.event : "");
  window.status = evt;
  if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  } else {
        if (element.contains(evt.toElement)) {
                return(false);
        } else {
                return(true);
        }
  }
}

function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

// for image show/hide

function getElementPosX(element) {
    var left = 0;
    if (element.offsetParent) {
        while (element.offsetParent) {
            left += element.offsetLeft;
            element = element.offsetParent;
        }
    } else if (element.x) {
        left += element.x;
    }
    return left;
}
function getElementPosY(element) {
    var top = 0;
    if (element.offsetParent) {
        while (element.offsetParent) {
            top += element.offsetTop;
            element = element.offsetParent;
        }
    } else if (element.y) {
        top += element.y;
    }
    return top;
}
function layoutImageBox(owner, box) {
    try {
        box.style.left = getElementPosX(owner) + 'px';
        box.style.top = getElementPosY(owner) + 'px';
        box.style.visibility = 'visible';
    } catch (e) {
//        alert(e);
    }
}
function showFullImage(owner, url, linkto) {
    try{
        imageBox = document.getElementById('image_box');
        imageBoxUrl = document.getElementById('image_box_url');
        var img = new Image();
        img.onload = function() {
            imageBox.src = img.src;
            w = img.width;
            h = img.height;
            max = 300.0;
            if (img.width > max) {
                scale = max / img.width;
                w *= scale;
                h *= scale;
            } else if (img.height > max) {
                scale = max / img.height;
                w *= scale;
                h *= scale;
            }
            imageBox.width = w;
            imageBox.height = h;
            img = null;
            layoutImageBox(owner, imageBox);
        }
        img.src = url;
        imageBoxUrl.href = linkto;
    } catch (e) {
//        alert(e);
    }
}

function text_change(object, resultFieldID, maxLength) {
    var ilen = maxLength - object.value.length;
    document.getElementById(resultFieldID).value = ilen>0?ilen:0;
    setMaxLength(object, maxLength);
}

function setMaxLength(object,length) 
{
    var tempString=object.value;
    if(tempString.length>length)
    {
        alert("Maximum "+ length +" characters.");
	
        if(tempString.length>length)
            tempString=tempString.substr(0,length);
            object.value=tempString;	
    }
} 			

function check_username_email() {
    var username = document.update.username.value;
    var email = document.update.email.value;
    var emailname = email.substring(0, email.indexOf('@'));
    var msg='<font color=red><b>Your username should not be same as your email name.</b></font>';
    var mess;
    if (document.all && document.all.showalert){
        if(username == emailname && username != '' && emailname != '') {
            document.all.showalert.style.display='';
            document.all.showalert.innerHTML=msg;
        }  else document.all.showalert.style.display='none';
    }else if (mess = document.getElementById('showalert')){
        if(username == emailname && username != '' && emailname != '') {
            mess.style.display='';
            mess.innerHTML=msg;
        } else mess.style.display='none';
    }
    if((username.length>0)&&(username == emailname)) { 
		if(Math.floor(Math.random() * 2)){
			document.update.username.focus();
		}else{
			document.update.email.focus();
		}
		}
}

function show_hide(obj_name){
	var obj = document.getElementById('s_h_'+obj_name);
	var showhide = document.getElementsByName(obj_name);
	var hideselect = document.getElementsByName(obj_name)[0];
	if(obj.style.display=='') {
		obj.style.display='none';
		document.getElementById('s_h_t_'+obj_name).innerHTML="<A HREF=\"javascript:show_hide('"+obj_name+"')\">Show</A>";	
		for (var i = 0;i < showhide.length;i++) {
		    showhide[i].checked = false;
		    if (showhide[i].value == "0") {
		        showhide[i].checked = true;
		    }
		}
		for (var i=0; i < hideselect.options.length; i++){
		    hideselect.options[i].selected = false;
		    if (i == (hideselect.options.length - 1)){
		        hideselect.options[i].selected = true;
		    }
		}
	} else {
		obj.style.display=''
		document.getElementById('s_h_t_'+obj_name).innerHTML="<A HREF=\"javascript:show_hide('"+obj_name+"')\">Hide</A>";						
	}
 }					

function show_hide_form() {
    try {
        var board = document.getElementById("past_board");
        if (board.style.display == 'none') {
               board.style.display = ''
        }else{
          board.style.display = 'none'
        }
    } catch(e) {
//        alert(e);
    }
}
// -->
function layoutImageBoxMenu(owner, box) {
    try {
        box.style.left = getElementPosX(owner) + owner.width + 'px';
        box.style.top  = getElementPosY(owner) + 'px';
        box.style.visibility = 'visible';
    } catch (e) {
//        alert(e);
    }
}
function showFullImageMenu(owner, url, height) {
    try{
        imageBox = document.getElementById('image_box');
//      imageBoxUrl = document.getElementById('image_box_url');
        var img = new Image();
        img.onload = function() {
            imageBox.src = img.src;
            w = img.width;
            h = img.height;
            max = 300.0;
            if (img.width > max) {
                scale = max / img.width;
                w *= scale;
                h *= scale;
            } else if (img.height > max) {
                scale = max / img.height;
                w *= scale;
                h *= scale;
            }
            imageBox.width = w;
            imageBox.height = h;
            img = null;
            layoutImageBoxMenu(owner, imageBox);
        }
        img.src = url;
//        imageBoxUrl.href = linkto;
    } catch (e) {
//        alert(e);
    }
}

function IsShowSelectProfileError(targetId,frm){
	if(IsSelectProfile(frm)){
		return true;
	} else {
	        window.location.href="#";
		target = document.getElementById(targetId);
		target.style.display="";
		return false;
	}
}

function IsSelectProfile(frm){
	var format = /^mark_[0-9]{1,}$/i;
	var userlists="";
	for (i = 0; i < frm.elements.length; i++) {
   	    try{
           if(format.test(frm.elements[i].name)){
             if(!frm.elements[i].checked) {
				 continue;
			 }
             var param=frm.elements[i].name.split("_");
			 if(userlists!=""){
			    userlists=userlists+"_";
			 }
			 userlists=userlists+param[1];
		   }
	    }catch(e){}
	}
    if(userlists=="") {
	   return false;
	} else {
		return true;
	}
}

function deleteBatch(theBox,theArray) {
    if(confirm('Are you sure you want to remove these emails from invite history?'))
    {
        theArray.delete_batch.value=1;
        theArray.submit();
    }
}

function copy2clip(Element) {
    inElement = document.getElementById(Element);
    if (inElement.createTextRange) {
         var range = inElement.createTextRange();
         if (range)
             range.execCommand('Copy');
         } 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="http://images.commercialless.com/_clipboard.swf" FlashVars="clipboard='+escape(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
  }
}
function ShowORHidden(obj){
	try{
		if(document.getElementById(obj+"_trtag").style.display == 'none'){
			document.getElementById(obj+"_trtag").style.display="";
		}else{
			document.getElementById(obj+"_trtag").style.display="none";
		}
	}catch(err){}
}

function copy_clip(copytext){
   text2copy = copytext.value;
	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="http://images.commercialless.com/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
	copytext.select();
        //alert("The hyperlink address that you copy is:\n\n"+text2copy);
}

function jquery_show_search_omitted_profile (match_id){
    jQuery("#proflie_show_" + match_id).hide();
    jQuery.ajax({
        type: "POST",
        url: "/_process_user_info_by_jquery",
        data: "action=search_user_show&match_id=" + match_id,
        success: function(){
        }
    });
}


function jquery_show_profiles ( frm ) {
    var format = /^mark_[0-9]{1,}$/i;
    for (i = 0; i < frm.elements.length; i++) {
        try {
           if(!format.test(frm.elements[i].name) || !frm.elements[i].checked)
             continue;
           var param=frm.elements[i].name.split("_");
           var match_id = param[1]
           jQuery("#proflie_show_" + match_id).hide();
           frm.elements[i].checked = false;
           jQuery.ajax({
              type: "GET",
              url: "/_process_user_info_by_jquery?action=search_user_show&match_id=" + match_id,
              success: function(data){
                  jQuery("#proflie_hide_" + data).show();
               }
           }); 
        }catch(e){}
    }
}

function dd(show) {
   document.getElementById('min'+show).style.display=document.getElementById('min'+show).style.display?"":"none";
   document.getElementById('max'+show).style.display=document.getElementById('max'+show).style.display?"":"none";
}

function highlightStatus(status) {
    var http_request;
    http_request=getXMLHttpRequest();
    http_request.open('GET', '/highlight_status_?status='+status+'&ajaxRequestUncache='+parseInt(Math.random() * 1000000), true);
        http_request.onreadystatechange =  function(){
            if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                    var info = http_request.responseText;
                    if(info==1){
                        window.location.reload();                
                    }
                } else {
                    alert('There was a problem with the request.');
            }
       }
    }
   http_request.send(null);
}

var starCount = new Array();
var rateArr = new Array("Poor", "Nothing Special", "Worth Watching", "Pretty Cool", "Awesome!");
var isRated = false;
var rateScore;
function showStars(id) {
	if(isRated)
		return false;

	for (var i = 0,j = 1; i < id ; i++,j++)
	{
		starCount[i] = document.getElementById("star_" + j);
		starCount[i].src = "http://images.commercialless.com/stars/red_star.gif";
	}
	for(var i = id,j = id+1; i < 5 ; i++,j++)
	{
		starCount[i] = document.getElementById("star_" + j);
		starCount[i].src = "http://images.commercialless.com/stars/gray_star.gif";
	}

	showRates(id);
}

function showRates(id){
  var msg = document.getElementById("message");
  msg.innerHTML = rateArr[id-1];
  
  rateScore = id;
}

function add_rate_count(video) {
    if(isRated == true) return false;
    
    var http_request;
    http_request=getXMLHttpRequest();
    http_request.open('GET', '/add_rate_count_?video='+video+'&score='+rateScore+'&ajaxRequestUncache='+parseInt(Math.random() * 1000000), true);
    for(var i=1;i<6;i++){
        if(i <= rateScore) {
            document.getElementById("a" + i).innerHTML = "<img border='0' src='http://images.commercialless.com/stars/red_star.gif'>";
         } else {
             document.getElementById("a" + i).innerHTML = "<img border='0' src='http://images.commercialless.com/stars/gray_star.gif'>";
          }
     }
        http_request.onreadystatechange =  function(){
            if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                    var info = http_request.responseText;
                    if(info.trim()=='1'){
                        document.getElementById("thanks").style.display = "block";
                        document.getElementById("message").style.display = "none";
                        document.getElementById("rate").style.display = "none";	                 
                    }
                } else {
                    alert('There was a problem with the request.');
            }
       }
    }
    http_request.send(null);
    isRated = true;
}

function email_replies(status) {
    var http_request;
    http_request=getXMLHttpRequest();
    http_request.open('GET', '/email_replies_status_?status='+status+'&ajaxRequestUncache='+parseInt(Math.random() * 1000000), true);
        http_request.onreadystatechange =  function(){
            if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                    var info = http_request.responseText;
                    if(info==1){
                        window.location.reload();                
                    }
                } else {
                    alert('There was a problem with the request.');
            }
       }
    }
   http_request.send(null);
}

function deleteConfirm()
{
    var count=0;
    var obj = document.forms.del_form.del;
    if (obj == null)
        return false;
    
    if (obj.length == null)//only one
	{
        if( obj.checked)
	        count=1;
	}else {
        for(i = 0; i < obj.length; i++)
		    if ( obj[i].checked )
                count++;
	}        
    if (count==0)
	{
        alert("Note:Please select the topics first!");
        return false;
	}
    else
        return confirm("Are you sure you want to remove the checked topics?");
}


function dyniframesize(iframename) {
  var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
  var FFVersion = getFFVersion.substr(0,2)
  //extra height in px to add to iframe in FireFox 1.0+ browsers
  var FFextraHeight=FFVersion>=0.1? 30 : 0 

  var pTar = null;
  if (document.getElementById){
    pTar = document.getElementById(iframename);
  }
  else{
    eval('pTar = ' + iframename + ';');
  }
  if (pTar && !window.opera){
    //begin resizing iframe
    pTar.style.display="block";
    
    if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){
      //ns6 syntax
      pTar.height = pTar.contentDocument.body.offsetHeight+FFextraHeight; 
      pTar.width = pTar.contentDocument.body.scrollWidth;
    }
    else if (pTar.Document && pTar.Document.body.scrollHeight){
      //ie5+ syntax
      pTar.height = pTar.Document.body.scrollHeight;
      pTar.width = pTar.Document.body.scrollWidth;
    }
  }
}

function jquery_add_to_favoriate ( match_id ) {
    //jQuery("#favoriate_add_" + match_id).hide();
    jQuery("#favoriate_add_" + match_id).html("<b>saving...</b>");

    jQuery.ajax({
        type: "POST",
        url: "/_process_user_info_by_jquery",
        data: "action=favoriate_add&match_id=" + match_id,
        success: function(){
            jQuery("#favoriate_add_" + match_id).html("<b>Already in <a target='_blank' href='/favorites'>your favorites</a></b>");
            jQuery("#favoriate_add_" + match_id).show();
        }
    });
}

function jquery_add_profiles_to_favoriate (){
    var match_id;
    var count = 0;
    for (var i = 0; i < document.f.del.length; i++){
        if( document.f.del[i].checked ) {
            match_id = document.f.del.value;
            jquery_add_to_favoriate( match_id );
            count ++;
        }
    }
    if ( count ==0 ){
        alert("You did not select profiles to add to your favorite profile list.")
    }
}

function jquery_hide_search_profile ( match_id ) {
    jQuery("#proflie_show_" + match_id).hide();
    //jQuery("#proflie_show_" + match_id).html("<b>loading...</b>");

    jQuery.ajax({
        type: "POST",
        url: "/_process_user_info_by_jquery",
        data: "action=search_user_hide&match_id=" + match_id,
        success: function(){
            jQuery("#proflie_hide_" + match_id).show();
        }
    });
}

function jquery_show_search_profile ( match_id ) {
    jQuery("#proflie_hide_" + match_id).hide();
    //jQuery("#proflie_show_" + match_id).html("<b>loading...</b>");

    jQuery.ajax({
        type: "POST",
        url: "/_process_user_info_by_jquery",
        data: "action=search_user_show&match_id=" + match_id,
        success: function(){
            jQuery("#proflie_show_" + match_id).show();
        }
    });
}

function jquery_un_block ( match_id ) {
//    jQuery("#proflie_show_" + match_id).html("<b>loading...</b>");
    jQuery.ajax({
        type: "POST",
        url: "/_process_user_info_by_jquery",
        data: "action=un_block&match_id=" + match_id,
        success: function(){
            jQuery("#proflie_show_" + match_id).hide();
        }
    });
}

function add_video_to_favorite(video) {
    var favorite = document.getElementById("is_in_favorite_"+video);
    var favorite_num = document.getElementById("favorite_num");
    jQuery.ajax({
          type: "POST",
          url: "/add_video_to_favorite_",
          data: "frompage=videos&video_to_favorite=" + video,
          success: function(info){
                favorite.innerHTML = "Already in <a href=\"/videos?my_favorite=1\">your favorites</a>";
                favorite_num.innerHTML = "(" + info + ")";
          }
      });
}
