function rolloverImg(id,src) {
  doc=document;
  el=doc.getElementById(id);
  if(!el.oldSrc) el.oldSrc=el.src;
  el.src=src;
  el.onmouseout=function() { restoreImg(); }
  doc.currentHover=id;
}
function restoreImg() {
  doc=document;
  id=doc.currentHover;
  el=doc.getElementById(id);
  el.src=el.oldSrc;
}

function trim(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}
String.prototype.ucfirst = function() {
   var x = this.split(/\s+/g);
   for(var i = 0; i < x.length; i++)
   {
      var parts = x[i].match(/(\w)(\w*)/);
 
      x[i] = parts[1].toUpperCase() + parts[2].toLowerCase();
   }
   return x.join(' ');
};
function urlencode(str) {
  return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function check_email(str) {
  at=str.indexOf('@');
  dot=str.indexOf('.',at);
  last_at=str.lastIndexOf('@');
  last_dot=str.lastIndexOf('.');
  if(at>0 && dot>0 && (dot-at)>1 && str.length-dot>1 && last_at==at && str.length>5) { valid='1' }
  else { valid='0'; }
  
  return valid
}
function pop_up(url,name,width,height) {  
  w = (document.body.clientWidth - width)/2;
  h = (document.body.clientHeight)/2;
  window.open(url,name,'width=' + width + ',height=' + height + ',menubar=no,left='+w+',top='+h+',screenX='+w+',screenY='+h+'');
}
function show_hide(id) {
  if(jQuery("#"+id).css("display")=="none") { jQuery("#"+id).css("display", "block"); }
  else { jQuery("#"+id).css("display", "none"); }
}
function add_emot(id_t,emot) {
  document.getElementById(id_t).value = document.getElementById(id_t).value + emot;
  document.getElementById(id_t).focus();
}
function show(id) {
  document.getElementById(id).style.display='block';
}
function hide(id) {
  document.getElementById(id).style.display='none';
}
function browser_detection() {
  browser_version = parseInt(navigator.appVersion);
  browser_type = navigator.appName;
  if (browser_type == "Microsoft Internet Explorer" && (browser_version >= 4)) {
   var type='ie';
  } 
  else {
   var type='other';
  }
  return type;
}

function preload_images(folder,pics) {
  pics=pics.split(";");
  for(i=0;i<pics.length;i++) {
    img=new Image();
    img.src=folder+pics[i];
  }
}
function changeValue(id) {
  d=document; el=d.getElementById(id);
  if(!el.oldValue) {
    el.oldValue=el.value;
  }
  val=el.oldValue;
  if(el.value==el.oldValue) {
    el.focus();
    el.value='';
    el.onblur=function() { returnValue(id) };
  }
}
function returnValue(id) {
  d=document; el=d.getElementById(id);
  if(el.value=='') el.value=el.oldValue;
}

function runFile(file) {
  d=document;
  ifr=d.getElementById('hiddenIfr');
  ifr.src=file;
}
function getElementPosition(elemID){
  var offsetTrail = document.getElementById(elemID);
  var offsetLeft = 0;
  var offsetTop = 0;
  while (offsetTrail){
   offsetLeft += offsetTrail.offsetLeft;
   offsetTop += offsetTrail.offsetTop;
   offsetTrail = offsetTrail.offsetParent;
  }
  if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
   offsetLeft += document.body.leftMargin;
   offsetTop += document.body.topMargin;
  }
  return {left:offsetLeft,top:offsetTop};
}

function getEl(el) {
  return document.getElementById(el);
}

function forms() {
  this.toCheck=new Array();
  this.checkPass=new Array();
  this.checkEmails=new Array();
  this.message="";
  this.alertMsg="";
  this.createMessage=true;
  
  this.check=function () {
    var clean=true;
    var d=document;
    var first;
    if(this.alertMsg=="") this.alertMsg="You must fill all the fields marked with ' * '";
    // check if filled
    for(i=0;i<this.toCheck.length;i++) {
      el=d.getElementById(this.toCheck[i]);
      if(trim(el.value)=="" || el.value==" ") {
        if(clean) first=el;
        clean=false;
        el.style.backgroundImage="url(/images/inp_check.gif)";
      }
      else {
        el.style.backgroundImage="url(/images/inp.gif)";
      }
    }
    // check passwords
    if(this.checkPass.length==2) {
      el1=d.getElementById(this.checkPass[0]);
      el2=d.getElementById(this.checkPass[1]);
      if(el1.value!==el2.value && clean==true) {
        alert("The password does not match with its confirmation");
        el1.style.backgroundImage="url(/images/inp_check.gif)";
        el2.style.backgroundImage="url(/images/inp_check.gif)";
        el1.focus();
        return false;
      }
      else {
        if(clean==true) {
          el1.style.backgroundImage="url(/images/inp.gif)";
          el2.style.backgroundImage="url(/images/inp.gif)";
        }
      }
    }
    // check emails
    ems=true;
    for(i=0;i<this.checkEmails.length;i++) {
      el=d.getElementById(this.checkEmails[i]);
      if(check_email(el.value)==0 && clean==true && ems==true) {
        el.style.backgroundImage="url(/images/inp_check.gif)";
        el.focus();
        alert("Email address incorrect");
        ems=false;
        return false;
      }
      else
        if(clean==true) el.style.backgroundImage="url(/images/inp.gif)";
    }
    if(clean==false) {
      first.focus();
      alert(this.alertMsg);
      return false;
    }
    else return true;
  }
  
  this.send=function (formId,urlSend,fRes) {
    d=document;
    f=d.getElementById(formId);
    if(!fRes) fRes="formResult";
    resDiv=d.getElementById(fRes);
    f.target="hiddenIfr";
    //if(urlSend.indexOf('?')!==-1) urlSend+="?formId="+formId; else urlSend+="&formId="+formId;
    f.action=urlSend;
    // show the loader
    resDiv.style.display='block';
    if(this.createMessage) resDiv.innerHTML="<div class='success'>"+this.message+"<br><center><img src='http://www.becomegorgeous.com/inc/files/loader.gif'></center></div>";
    f.style.display='none';
    
    // submit the form
    f.submit();
  }

}

function sapos(str) {
  if (typeof(str) !== "undefined" && str!==null) {
    str = str.replace("'", "&#39;");
    str = str.replace('"', '&#34;');
    return str;
  }
  else return '';
}
function nl2br(str) {
  if (typeof(str) !== "undefined" && str!==null) return (str + '').replace(/([^>]?)\n/g, '$1<br>\n');
}
function nobr(str) {
  if (typeof(str) !== "undefined" && str!==null) return str.replace(/<br>/gi, '').replace(/<br \/>/gi, '');
}

jQuery(document).ready(function() {
  // sprites
  refreshSprites();
  refreshSpritesCh();
});
function refreshSprites() {
  jQuery(".sprite").mouseover(function() {
    h=jQuery(this).height();
    jQuery(this).css("background-position", "0px -"+h+"px");
  });
  jQuery(".sprite").mousedown(function() {
    h=jQuery(this).height()*2;
    jQuery(this).css("background-position", "0px -"+h+"px");
    return false;
  });
  jQuery(".sprite").mouseout(function() {
    jQuery(this).css("background-position", "0px 0px");
  });
  jQuery(".sprite").mouseup(function() {
    jQuery(this).css("background-position", "0px 0px");
  });
}
function refreshSpritesCh() {
  jQuery(".sprite-choose").mouseover(function() {
    h=jQuery(this).height();
    if(!jQuery(this).hasClass("sprite-selected")) jQuery(this).css("background-position", "0px -"+h+"px");
  });
  jQuery(".sprite-choose").mousedown(function() {
    elem=jQuery(this);
    h=elem.height()*2;
    jQuery(".sprite-choose[name="+elem.attr("name")+"]").css("background-position", "0px 0px");
    jQuery(".sprite-choose[name="+elem.attr("name")+"]").removeClass("sprite-selected");
    elem.css("background-position", "0px -"+h+"px");
    elem.addClass("sprite-selected");
    return false;
  });
  jQuery(".sprite-choose").mouseout(function() {
    elem=jQuery(this);
    if(!elem.hasClass("sprite-selected")) elem.css("background-position", "0px 0px");
    else {
      h=elem.height()*2;
      elem.css("background-position", "0px -"+h+"px");
    }
  });
  jQuery(".sprite-choose").mouseup(function() {
    elem=jQuery(this);
    if(!elem.hasClass("sprite-selected")) elem.css("background-position", "0px 0px");
  });
}
function spriteIt(elem) {
  jQuery("#"+elem).mouseover(function() {
    h=jQuery(this).height();
    jQuery(this).css("background-position", "0px -"+h+"px");
  });
  jQuery("#"+elem).mousedown(function() {
    h=jQuery(this).height()*2;
    jQuery(this).css("background-position", "0px -"+h+"px");
    return false;
  });
  jQuery("#"+elem).mouseout(function() {
    jQuery(this).css("background-position", "0px 0px");
  });
  jQuery("#"+elem).mouseup(function() {
    jQuery(this).css("background-position", "0px 0px");
  });
}

function overlay(elem, w, clickclose) {
  //msg="<a href='javascript:;' onclick='jQuery.unblockUI()' id='close-blockUI' class='spr-close sprite right'></a>"+jQuery('#'+elem).html();
  if(w=="" || w=="NULL" || w=="undefined" || !w) w=500;
  $.blockUI({ 
    message: $('#'+elem).html(),
    css: {
      left: (jQuery(window).width() - w) /2 + 'px', 
      width: w+'px' 
    }
  });
  //spriteIt("close-blockUI");
  if(clickclose!==false) jQuery('.blockOverlay').attr('title','Click to close').click(jQuery.unblockUI); 
}

function confirm2(conftext, confok, callback) {
  if(confok=="" || typeof(confok)=="undefined") confok="Yes";
  w=500;
  theText="<span class='blhd'>Confirm action</span>"
          +"<span class='block t14 grey2' style='padding:5px; margin-bottom:10px;'>"
          +conftext
          +"<br><br>"
          +"<center><input type='button' onclick=\""+callback+"\" value='"+confok+"' class='submit' style='font-size:17px'>&nbsp;&nbsp;<input type='button' class='submit' value='Cancel' onclick='jQuery.unblockUI()' style='font-size:17px'></center>"
          +"</span>";
  jQuery.blockUI({
    message: theText,
    css: {
      left: (jQuery(window).width() - w) /2 + 'px', 
      width: w+'px' 
    },
    overlayCSS: {
      backgroundColor: '#000',
      opacity:          0,
      cursor:          'default'
    }
  });
  jQuery('.blockOverlay').attr('title','Click to close').click(jQuery.unblockUI); 
  return false;
}

// Comments
jQuery(document).ready(function () {
  if(jQuery("#comments_form")) {
    jQuery("#comments_form").submit(function() {
      if(trim(jQuery("#comments_text").val())=="") {
        alert("Please write a comment");
        jQuery("#comments_text").focus();
        return false;
      }
      else {
        comm=jQuery("#comments_text").val();
        p_id=jQuery("#comments_p_id").val();
        pentru=jQuery("#comments_pentru").val();
        emailto=jQuery("#comments_emailto").val();
        emailpage=jQuery("#comments_emailpage").val();
        comlimit=jQuery("#comments_limit").val();
        comwidth=jQuery("#comments_width").val();
        
        overlay("comments_loader", 500, false);
        
        jQuery.post("/inc/ajax/add_comment.php", 
        { 
          comment_message:comm,
          emailto:emailto,
          p_id:p_id,
          pentru:pentru,
          emailpage:emailpage,
          comlimit:comlimit,
          comwidth:comwidth,
          rand:Math.random() 
        }, 
        function(data) {
          setTimeout(function() {
            jQuery.unblockUI();
            window.location='#comments_form';
            jQuery("#theComments").prepend(data);
            jQuery("#comments_form").html("<font class='t14 bld grey'>Comment posted</font><br><br>");
          }, 1000);
        });
        
        return false;
      }
    });
  }
});
function delComment(comid, by) {
  ok=confirm("Are you sure you want to delete this comment?");
  if(ok) {
    jQuery.post("/inc/ajax/del_comment.php",
    {
      comid:comid,
      by:by
    },
    function() {
        jQuery("#comment-text"+comid).html("<em>Comment deleted by <b>"+by+"</b></em>");
        jQuery("#comment-delete"+comid).html("");
      }
    );
  }
}

/*
 * image uploader and crop
 * USE:
 * <span name='[imginputid]' class='imguploader [imginpudid]'>
 *  <input type='hidden' name='folder' value='[folder]'> (neccessary)
 *  <input type='hidden' name='thumbwidth' value='[thumbwidth]'> (optional. default: 100)
 *  <input type='hidden' name='imgwidth' value='[imgwidth]'> (optional. default: 560)
 *  <input type='hidden' name='callback' value='[callback_function]'> (optional. use imgsrc to get the src. eg: function(imgsrc) { alert("File: "+imgsrc+" uploaded") })
 * </span>
 */
function crop(imgid, width, cropcallback) {
  if(width==null || typeof(width)=="undefined") width="100";
  if(cropcallback==null || typeof(cropcallback)=="undefined") cropcallback="";
  s=jQuery("#"+imgid).attr("src");
  w=600;
  msg="<span class='blocker' style='display:block' id='loginBlocker'>"
     +"<font class='blhd'>Crop image</font>"
     +"<br><center><img src='"+s+"' id='cropping_"+imgid+"'></center>"
     +"<div style='padding:10px'>"
     +"<div class='clearfix' style='margin-bottom:10px;'>"
     +"<font class='crophd'>Choose crop layout</font>"
     +"<span class='crop-layout-span'>"
     +"<font>Portrait</font>"
     +"<a href='javascript:;' onclick='crop.cropit(\"cropping_"+imgid+"\", 0.75)' class='sprite-choose spr-crop_layout1 sprite-selected' name='sprite-layout'></a>"
     +"<a href='javascript:;' onclick='crop.cropit(\"cropping_"+imgid+"\", 0.66)' class='sprite-choose spr-crop_layout2' name='sprite-layout'></a>"
     +"</span>"
     +"<span class='crop-layout-span'>"
     +"<font>Square</font>"
     +"<a href='javascript:;' onclick='crop.cropit(\"cropping_"+imgid+"\", 1)' class='sprite-choose spr-crop_layout3' name='sprite-layout'></a>"
     +"</span>"
     +"<span class='crop-layout-span' style='width:200px'>"
     +"<font>Landscape</font>"
     +"<a href='javascript:;' onclick='crop.cropit(\"cropping_"+imgid+"\", 1.33)' class='sprite-choose spr-crop_layout4' name='sprite-layout'></a>"
     +"<a href='javascript:;' onclick='crop.cropit(\"cropping_"+imgid+"\", 1.5)' class='sprite-choose spr-crop_layout5' name='sprite-layout'></a>"
     +"</span>"
     +"</div>"
     +"<center><a href='javascript:;' onclick='crop.cropsend(\""+imgid+"\")' class='sprite spr-cropbutton' id='send_crop'></a></center>"
     +"<input type='hidden' id='crop_x'><input type='hidden' id='crop_y'>"
     +"<input type='hidden' id='crop_x2'><input type='hidden' id='crop_y2'>"
     +"<input type='hidden' id='crop_w'><input type='hidden' id='crop_h'>"
     +"<input type='hidden' id='crop_imgwidth' value='"+width+"'>"
     +"<input type='hidden' id='crop_callback' value=\""+cropcallback+"\">"
     +"</div>"
     +"</span>";
  jQuery.blockUI({
    message: msg,
    css: {
      left: (jQuery(window).width() - w) /2 + 'px',
      top: 10+"px",
      width: w+'px' 
    },
    overlayCSS: {
      cursor:"default"
    }
  });
  
  crop.cropit("cropping_"+imgid);
  refreshSpritesCh();
  refreshSprites();
}
crop.cropit=function(imgid, ratio) {
  if(ratio==null) ratio=0.75;
  jQuery('#'+imgid).Jcrop({
        onChange: crop.showCoords,
        onSelect: crop.showCoords,
        aspectRatio: ratio,
        allowSelect:false,
        setSelect: [ 0, 0, 75, 100 ]
  });
}
crop.showCoords=function(c)
  {
    jQuery('#crop_x').val(c.x);
    jQuery('#crop_y').val(c.y);
    jQuery('#crop_x2').val(c.x2);
    jQuery('#crop_y2').val(c.y2);
    jQuery('#crop_w').val(c.w);
    jQuery('#crop_h').val(c.h);
  };
crop.cropsend=function(imgid) {
  s=jQuery("#"+imgid).attr("src");
  jQuery("#send_crop").css("opacity", 0.3);
  jQuery("#send_crop").css("cursor", "wait");
  getEl("send_crop").onclick=function() { };
  jQuery.post("/inc/imguploader/crop.php",
  { 
    x:jQuery('#crop_x').val(),
    y:jQuery('#crop_y').val(),
    x2:jQuery('#crop_x2').val(),
    y2:jQuery('#crop_y2').val(),
    w:jQuery('#crop_w').val(),
    h:jQuery('#crop_h').val(),
    callback:jQuery('#crop_callback').val(),
    imgwidth:jQuery('#crop_imgwidth').val(),
    imgsrc:s
  }, 
  function(data) {
    cropcallback="";
    spanid=imgid.substr(0, imgid.length-6);
    if(data.substr(0, 2)=="[c") {
      i=data.indexOf("]");
      cropcallback=data.substr(10, i-10);
      data=data.substr(i+1, data.length);
    }
    jQuery.unblockUI();
    jQuery("#"+imgid).attr("src", data);
    jQuery("."+spanid).append("<br><a class='red t11' href='javascript:;' onclick='imguploader_remove(\""+imgid+"\")'>(remove photo)</a>");
    jQuery("#"+imgid).removeClass("hidden");
    jQuery("#"+imgid).attr("width", jQuery('#crop_imgwidth').val());
    imgsrc=data;
    jQuery("."+spanid).addClass("imguploaded");
    if(cropcallback!=="") eval(stripslashes(cropcallback));
  });
}
function imguploader_remove(imgid) {
  imgsrc=jQuery("#"+imgid).attr("src");
  jQuery.post("/inc/imguploader/del.php",
  {
    imgsrc:imgsrc,
    token:jQuery("#s_token").val()
  },
  function(data) {
    spanid=imgid.substr(0, imgid.length-6);
    jQuery("."+spanid).html(jQuery("."+spanid+"_temp").html());
    jQuery("."+spanid).removeClass("imguploaded");
    imguploader_refresh();
    if(jQuery("."+spanid+"_temp input[name='callback_delete']").length>0) {
      eval(jQuery("."+spanid+"_temp input[name='callback_delete']").val());
    }
  }
  );
}

function imguploader_updateWidth(w, fileid) {
  jQuery("#imageuploaderform"+fileid+" input[name='imgwidth']").val(w);
}
function imguploader_refresh() {
  jQuery(".imguploader").each(function() {
   if(jQuery("[name="+jQuery(this).attr("name")+"] form").length==0 && !jQuery(this).hasClass("imguploaded")) {
    elem=jQuery(this);
    elemname=elem.attr("name");
    fileid=elem.attr("name");
    filefolder=jQuery("[name="+elemname+"] input[name=folder]").val();
    imgthumbwidth=jQuery("[name="+elemname+"] input[name=thumbwidth]").val();
    imgwidth=jQuery("[name="+elemname+"] input[name=imgwidth]").val();
    cropcallback=jQuery("[name="+elemname+"] input[name=callback]").val();
    if(cropcallback==null) cropcallback="";
    if(imgthumbwidth==null) imgthumbwidth=100;
    if(imgwidth==null) imgwidth=560;
    if (jQuery("." + elemname + "_temp").length == 0) {
      jQuery("body").append("<span class='" + elemname + "_temp hidden'>"+elem.html()+"</span>");
    }
    elem.html("<form method='post' style='margin:0px;padding:0px;' action='/inc/imguploader/upload.php' enctype='multipart/form-data' target='hiddenIfr' name='imageuploaderform' id='imageuploaderform"+fileid+"'>"
             +"<input type='file' name='imguploader_pic'>"
             +"<input type='submit' class='t12 bld grey2' value='Upload' onclick='this.disabled=\"disabled\"'>"
             +"<input type='hidden' name='imguploader_id' value='"+fileid+"'>"
             +"<input type='hidden' name='folder' value='"+filefolder+"'>"
             +"<input type='hidden' name='thumbwidth' value='"+imgthumbwidth+"'>"
             +"<input type='hidden' name='imgwidth' value='"+imgwidth+"'>"
             +"<input type='hidden' name='callback' value=\""+cropcallback+"\">"
             +"<input type='hidden' id='"+fileid+"' value=''>"
             +"</form>"
             +"<span class='hidden' id='imguploaderform"+fileid+"_loader'><img src='/images/loaders/small.gif'></span>");
   }
  });
  jQuery("form[name=imageuploaderform]").each(function() {
    elem=jQuery(this);
    elem.submit(function() {
      elem=jQuery(this);
      fileid=elem.attr("id").replace("imageuploaderform", "");
      //elem.css("display","none");
      jQuery("#imguploaderform"+fileid+"_loader").css("display","block");
    });
  });
}

jQuery(document).ready(function() {
  imguploader_refresh();
});


function varDump(variable, maxDeep)
{
  var deep = 0;
  var maxDeep = maxDeep || 5;

  function fetch(object, parent)
  {
    var buffer = '';
    deep++;

    for (var i in object) {
      if (parent) {
        objectPath = parent + '.' + i;
      } else {
        objectPath = i;
      }

      buffer += objectPath + ' (' + typeof object[i] + ')';

      if (typeof object[i] == 'object') {
        buffer += "\n";
        if (deep < maxDeep) {
          buffer += fetch(object[i], objectPath);
        }
      } else if (typeof object[i] == 'function') {
        buffer += "\n";
      } else if (typeof object[i] == 'string') {
        buffer += ': "' + object[i] + "\"\n";
      } else {
        buffer += ': ' + object[i] + "\n";
      }
    }

    deep--;
    return buffer;
  }

  if (typeof variable == 'object') {
    return fetch(variable);
  }

  return '(' + typeof variable + '): ' + variable + "\n";
}
function stripslashes (str) {
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
}

function ucfirst (str) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
Array.prototype.interchange = function(from, to){
  data=this[from];
  this[from]=this[to];
  this[to]=data;
  return this;
}

function array_search (needle, haystack, argStrict) {
    var strict = !!argStrict;
    var key = '';
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            return key;
        }
    }
    return false;
}

Array.prototype.pushelem = function(elem){
  this.length++;
  this[this.length]=elem;
  return this;
}

function alert_msg(alert_title, alert_msg) {
  msg="<span class='alert_block'>"
    +"<span class='alert_hd'>"+alert_title+"</span>"
    +"<p>"+alert_msg+"</p>"
    +"<center>&nbsp;<a href='javascript:;' onclick='$.unblockUI()' class='sprite spr-ok'></a></center>"
    +"</span>";
  
  $.blockUI({
    message: msg,
    css: {
      border: "none",
      backgroundColor: "transparent"
    },
    overlayCSS: {
      backgroundColor: "#fff",
      opacity: 0.5,
      cursor: "default"
    }
  });
  refreshSprites();
  $.sound.play("/inc/sounds/beep.WAV");
}


function add_counter(elemid, limit) {
  $("#"+elemid).after("<span id='"+elemid+"_counter' style='font-size:10px; color:#777'>"+limit+" characters left</span>");
  $("#"+elemid).keydown(function() { input_counter(elemid, limit) });
  $("#"+elemid).keyup(function() { input_counter(elemid, limit) });
  $("#"+elemid).change(function() { input_counter(elemid, limit) });
  input_counter(elemid, limit);
}

(function($)  {
 $.fn.limit = function(limit) {
   add_counter(this.attr("id"), limit);
 };
})(jQuery);

function input_counter(elemid, limit) {
  elem=$("#"+elemid);
  if(elem.val().length>limit) {
    elem.val(elem.val().substr(0, limit));
  }
  counter_val=(limit-elem.val().length)+" characters left";
  $("#"+elemid+"_counter").html(counter_val);
}

$(document).ready(function() {
  $("#search_top").submit(function() {
    el=$(this);
    key_el=$("#search_top input[name='keywords']");
    if(key_el.val().length<3) {
      alert_msg("Error", "The keyword has to be at least 3 characters long");
      key_el.focus();
      return false;
    }
    else {
      el.submit();
    }
  });
});

function horiz_slider(elemid, dir, slidesnr) {
  elem=$("#"+elemid);
  if(typeof(elem.data("sliding"))=="undefined") elem.data("sliding", false)
  if (!elem.data("sliding")) {
    elem.data("sliding", true);
    
    elem_h=250;
    slide_wrapper=$("#"+elemid+"_wrapper");
    cr_top=slide_wrapper.css("top");
    cr_top=parseInt(cr_top);
    if(cr_top==null || isNaN(cr_top)) cr_top=0;
    if(dir=="down") top_go=cr_top-elem_h;
    else top_go=cr_top+elem_h;
    if(top_go>0) top_go=-elem_h*(slidesnr-1);
    if(top_go<-elem_h*(slidesnr-1)) top_go=0;
    
    slide_wrapper.animate({
        top: top_go+"px"
      }, 
      800, 
      "easeInOutExpo", 
      function(){
        elem.data("sliding", false);
    });
  }
}

jQuery(function($) {
    $('.home_arts_sidebar')
        .bind('mousewheel', function(event, delta) {
            var dir = delta > 0 ? 'up' : 'down',
                vel = Math.abs(delta);
            horiz_slider('home_slider', dir, 5);
            return false;
        });
});

function form_check() {
  this.fields = new Array();
  this.check = function () {
    $("form input[type='submit']").attr("disabled", "disabled");
    
    valid=true;
    invalid=new Array();
    for(i=0;i<this.fields.length;i++) {
      if(!(this.valid($("#"+this.fields[i]).val()))) {
        valid=false;
        invalid.push(this.fields[i]);
      }
      else $("#"+this.fields[i]).addClass("inp").removeClass("inp_bad");
    }
    if(!valid) {
      for(i=0;i<invalid.length;i++) {
        $("#"+invalid[i]).addClass("inp_bad");
      }
      alert_msg("Error", "All fields are required");
      $("#"+invalid[0]).focus();
      $("form input[type='submit']").attr("disabled", false);
      return false;
    }
    else return true;
  }
  this.valid=function (val) {
    if(trim(val)=="") return false;
    else return true;
  }
}

(function($)  {
 $.fn.check_form = function(to_check) {
   this.bind("submit", function() {
    f=new form_check();
    f.fields=to_check.split(",");
    if(f.check()) this.submit();
    return false;
  });
 };
})(jQuery);

function login() {
  msg="<span class='blocker' id='loginBlocker'>"+
  "<font class='blhd'><a href='javascript:;' onclick='jQuery.unblockUI()' id='close-blockUI' class='spr-close sprite'></a><img src='/icon/lock_unlock.png' class='icon'>Login</font>"+
  "<span class='block' style='padding:8px;'>"+
  "<form method='post' action='' onsubmit='return blockerLogin()' id='blockerLoginForm' class='form'>"+
  "<label for='blocker-login-email'>Email: </label><input type='text' name='blocker-login-email' id='blocker-login-email' class='inp'>"+
  "<br>"+
  "<label for='blocker-login-password'>Password: </label><input type='password' name='blocker-login-password' id='blocker-login-password' class='inp'>"+
  "<br>"+
  "<label></label>"+
  "<input type='submit' class='submit' value='Login' />"+
  "<input type='button' class='submit' value='Cancel' onclick='jQuery.unblockUI()' />"+
  "<br>"+
  "<span class='clearfix'>"+
  "<span class='right tright t12 grey'>"+
  "Forgot your password? <br />"+
  "<a href='/recover-password' style='color:red'>Recover it!</a>"+
  "</span>"+
  "<span class='tleft t12'>Not a member?"+
  "<br />"+
  "<a href='/register/'>Click here to <font color='red'>Join Us</font>!</a>"+
  "</span>"+
  "</span>"+
  "</form>"+
  "<span class='hidden block' id='blockerLoginLoader' class='hidden'><center><br><br><font class='t15 bld grey'>Please wait..</font><br><br><img src='/images/loaders/1.gif' alt=''></center><br><br><br></span>"+
  "</span>"+
  "</span>";
  
  
  $.blockUI({
    message: msg,
    css: {
      border: "1px solid #ccc",
      backgroundColor: "#fff"
    },
    overlayCSS: {
      backgroundColor: "#fff",
      opacity: 0.5,
      cursor: "default"
    }
  });
  refreshSprites();
}
function blockerLogin() {
  $("#blockerLoginForm").addClass("hidden");
  $("#blockerLoginLoader").removeClass("hidden");
  jQuery.post("/inc/ajax/login.php", 
    { 
      email:jQuery('#blocker-login-email').val(),
      password:jQuery('#blocker-login-password').val(),
      rand:Math.random() 
    }, 
    function(data) {
      if(trim(data)=='yes') {
        window.location.reload();
      }
      else {
        alert("Error: invalid email / password");
        $("#blockerLoginForm").removeClass("hidden");
        $("#blockerLoginLoader").addClass("hidden");
      }
  });
  return false;
}

// AVATAR
function update_avatar(elem_id) {
  el=$("#"+elem_id);
  $("input[type='submit']").attr("disabled", true);
  if($("#new_avatar").val()=="") {
    alert_msg("Error", "Please choose an avatar");
    $("input[type='submit']").attr("disabled", false);
  }
  else {
    el.attr("target", "hiddenIfr");
    el.attr("action", "/inc/ajax/update_avatar.php?elem_id="+elem_id);
    el.submit();
    
    
    msg="<span class='blocker' id='loginBlocker'>"+
    "<font class='blhd'>Loading..</font>"+
    "<span class='block' style='padding:8px;'>"+
    "<span class='block' class='hidden'><center><br><br><font class='t15 bld grey'>Please wait..</font><br><br><img src='/images/loaders/1.gif' alt=''></center><br><br><br></span>"+
    "</span>"+
    "</span>";
    
    $.blockUI({
      message: msg,
      css: {
        border: "1px solid #ccc",
        backgroundColor: "#fff"
      },
      overlayCSS: {
        backgroundColor: "#fff",
        opacity: 0.5,
        cursor: "default"
      }
    });
  }
  return false;
}
function cropAvatar(avdir) {
  msg="<span class='blocker' id='cropAvatarBlocker'>"+
  "<font class='blhd'>Crop avatar</font>"+
  "<span class='block' style='padding:8px;'>"+
  "<center>"+
  "<img src='"+avdir+"large_temp.jpg' id='crop_av_pic'>"+
  "<br><br><input type='button' onclick='cropAvatar.send(\""+avdir+"\")' class='t20' value='Crop'>"+
  "<input type='hidden' id='crop_x'><input type='hidden' id='crop_y'><input type='hidden' id='crop_x2'><input type='hidden' id='crop_y2'>"+
  "<input type='hidden' id='crop_w'><input type='hidden' id='crop_h'>"+
  "</center>"+  
  "<span class='hidden block' id='blockerLoader' class='hidden'><center><br><br><font class='t15 bld grey'>Please wait..</font><br><br><img src='/images/loaders/1.gif' alt=''></center><br><br><br></span>"+
  "</span>"+
  "</span>";
  
  $.blockUI({
    message: msg,
    css: {
      border: "1px solid #ccc",
      backgroundColor: "#fff",
      top: "30px"
    },
    overlayCSS: {
      backgroundColor: "#fff",
      opacity: 0.5,
      cursor: "default"
    }
  });
  
  jQuery('#crop_av_pic').Jcrop({
        onChange: crop.showCoords,
        onSelect: crop.showCoords,
        aspectRatio: 1,
        allowSelect:false,
        setSelect: [ 0, 0, 100, 100 ]
  });
}
cropAvatar.send=function(avdir) {
  imgid="crop_av_pic";
  $("#cropAvatarBlocker center").addClass("hidden");
  $("#blockerLoader").removeClass("hidden");
  $("#blockerLoader center").removeClass("hidden");
  $.post("/inc/ajax/crop_avatar.php",
  { 
    x:jQuery('#crop_x').val(),
    y:jQuery('#crop_y').val(),
    x2:jQuery('#crop_x2').val(),
    y2:jQuery('#crop_y2').val(),
    w:jQuery('#crop_w').val(),
    h:jQuery('#crop_h').val(),
    avdir:avdir
  }, 
  function(data) {
    $("input[type='submit']").attr("disabled", false);
    $.unblockUI();
    $("#new_av_form label").html("New avatar: ");
    $("#new_av_form input[type='file']").replaceWith("<img src='"+avdir+"large.jpg'>");
    $("#new_av_form input[type='submit']").remove();
    alert("Your avatar was successfully updated\n! It may take a few hours before your avatar will change permanently on our site !");
  });
}

function chooseLang() {
  $("#choose_lang ul").slideToggle();
}

function checkCheckboxes(self, chclass) {
  state=$(self).attr("checked");
  $("."+chclass).each(function() {
    $(this).attr("checked", state);
  });
}

$(document).ready(function() {
 jQuery("#social_box_icons a").css("opacity", 0.3);
 jQuery("#social_box_icons a").mouseover(function() { jQuery(this).animate({opacity: 1}) });
 jQuery("#social_box_icons a").mouseout(function() { jQuery(this).animate({opacity: 0.3}) });
});


function fb_connect() {
  window.location="/fb/connect.php";
}

preload_images("/images/loaders/","1.gif;small.gif");
preload_images("/images/sprites/", "ok.gif")