var date=new Date();

function trim( str, charlist ) {
    var whitespace;

    if(!charlist){
        whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    } else{
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }

	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
		str = str.substring(i);
		break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
    	}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function is_integer ( mixed_var ) {
  return !isNaN ( parseInt( Math.abs( trim ( mixed_var ) ) ) );
}

function is_numeric( mixed_var ) {
  return !isNaN( mixed_var );
}

function in_array(needle, haystack, strict) {
    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}

function MM_swapImgRestore() {
	var i,x,a = document.MM_sr;

	for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_preloadImages() {
	var d = document;

	if (d.images) {
		if (!d.MM_p) d.MM_p = new Array();
		var i,j = d.MM_p.length,a = MM_preloadImages.arguments;

		for (i = 0; i < a.length; i++)
		if (a[i].indexOf("#") != 0) {
			d.MM_p[j] = new Image;
			d.MM_p[j++].src = a[i];
		}
	}
}

function MM_findObj(n, d) {
	var p,i,x;

	if (!d) d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p+1)].document;
		n = n.substring(0,p);
	}
	if (!(x = d[n]) && d.all) x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n,d.layers[i].document);
	if (!x && d.getElementById) x = d.getElementById(n);

	return x;
}

function MM_showHideLayers() {
	var i,p,v,obj,args = MM_showHideLayers.arguments;

	for (i = 0; i < (args.length-2); i += 3)

	if ((obj = MM_findObj(args[i])) != null) {
		v = args[i+2];

    if (obj.style) {
    	obj = obj.style;
    	v = (v == 'show') ? 'visible' : (v = 'hide') ? 'hidden' : v;
    }

    obj.visibility = v; }
}

function MM_swapImage() {
	var i,j = 0,x, a = MM_swapImage.arguments;
	document.MM_sr = new Array;

	for (i = 0; i < (a.length-2); i += 3)
	if ((x = MM_findObj(a[i])) != null) {
		document.MM_sr[j++] = x;
		if (!x.oSrc) x.oSrc = x.src;
		x.src = a[i+2];
	}
}

function ks_over(_id) {
  document.getElementById(_id).style.borderColor="green";
}

function ks_out(_id) {
  document.getElementById(_id).style.borderColor="#cccccc";
}

function tooltips(name,  offsetLeft, offsetTop, alignment, iter, time, popupLatency, hideLatency, staticHover, popupHover, onInit, onPopup, onHide){
  var ott = document.getElementById(name);
  ott.alignment = alignment;
  ott.main = document.getElementById(name+"PopUp")
  ott.bottom = document.getElementById(name+"Anim")
  ott.oX = offsetLeft
  ott.oY = offsetTop;
  ott.iter = iter;
  ott.time = time;

  ott.popupLatency = popupLatency;
  ott.hideLatency = hideLatency;
  ott.onPopup = onPopup;
  ott.onHide = onHide;

  ott.onmouseover = function(){
    if (staticHover)
      if(staticHover!=''){
        ott.className_=ott.className;
        ott.className=staticHover;
      };
    popup(ott,true);
  }
  ott.onmouseout = function(){
    if (staticHover)
      if(staticHover!='') {ott.className=ott.className_};
      popup(ott,false);
  }

  if(document.all){
    ott.onactivate = ott.onmouseover
    ott.ondeactivate = ott.onmouseout
  }else{
    ott.onfocus = ott.onmouseover
    ott.onblur = ott.onmouseout
  }

  ott.main.onmouseover = function(){
    if (popupHover)
      if(popupHover!=''){
        ott.main.className_=ott.main.className;ott.main.className=popupHover;
      };
    popup(ott,true);
  }

  ott.main.onmouseout = function(){
    if (popupHover)
      if(popupHover!=''){
        ott.main.className=ott.main.className_
      };
    popup(ott,false);
  }

  callClient(onInit, ott)
}

function callClient(name, ott){
  if(name!=null &&  name!="")
    eval( name + "(ott);");
}

function setPosition(ott, obj){
  obj.style.top = ott.oY + ott.offsetHeight+ "px";
  obj.style.left = ott.oX + (ott.offsetWidth - obj.offsetWidth )*(1+ott.alignment)/2 + "px";
}

function popup(ott,value){
  if(ott.timer!=null ) window.clearTimeout(ott.timer)
  if(value){
    if(ott.status=="on") return
    var timeout = (ott.status=="active") ? 0 : ott.popupLatency
    if(ott.iter>0 && ott.time>0)
      ott.timer = window.setTimeout(function(){animStart(ott,true,ott.bottom.curIter);ott.style.zIndex = "999";},timeout)
    else
      ott.timer = window.setTimeout(function(){setVisibility(ott,true);},timeout)
  }else{
    if(ott.status=="off") return
    var timeout = (ott.status=="active") ? 0 : ott.hideLatency
    if(ott.iter>0 && ott.time>0)
      ott.timer = window.setTimeout(function(){animStart(ott,false,ott.bottom.curIter);},timeout)
    else
      ott.timer = window.setTimeout(function(){setVisibility(ott,false);},timeout)
  }
}

function setVisibility(ott, value){
  if(value==true){
    setPosition(ott,ott.main);
    ott.main.style.visibility = "visible";
    ott.style.zIndex = "999";
  }else{
    ott.main.style.visibility = "hidden";
    ott.style.zIndex = "0";
    ott.main.style.left = "-10000px";
  }
}

function animStart(ott, inout, curIter){
  if(ott.bottom.timer!=null) window.clearTimeout(ott.bottom.timer);
  if(curIter==null) curIter=0;
  if(ott.status !="active"){
    ott.status ="active";
    ott.bottom.style.visibility = "visible";
    ott.main.style.visibility="hidden";
  }

  if(curIter<0 || curIter>ott.iter ){
    ott.bottom.curIter = (curIter<1) ? 0 : ott.iter;
    ott.status = (ott.bottom.curIter==ott.iter) ? "on": "off";
    ott.bottom.style.visibility = "hidden";
    setPosition(ott,ott.main);
    ott.style.zIndex=(ott.bottom.curIter==ott.iter) ? "999" : "0";
    if(ott.bottom.curIter==ott.iter){
      ott.status = "on";
      setVisibility(ott,true);
      callClient(ott.onPopup, ott)
    }else{
      ott.status = "off";
      setVisibility(ott,false);
      callClient(ott.onHide, ott)
    }
  }else{
    var per = curIter*(95/ott.iter)+ 5;
    ott.bottom.style.visibility = "hidden";
    ott.bottom.style.width=ott.main.offsetWidth/100*per + "px";
    ott.bottom.style.height=ott.main.offsetHeight/100*per + "px";
    setPosition(ott, ott.bottom);
    ott.bottom.style.visibility = "visible";
    var timeout = (per==100 ) ? 0 : ott.time - (ott.time/(ott.iter)*(curIter));
    curIter += (inout) ? 1:-1;
    ott.bottom.timer = window.setTimeout(function(){animStart(ott, inout, curIter)},timeout);
    ott.bottom.curIter = curIter;
  }
}

function clearOption(sel) {
	if (sel.length) sel.length=0;
}
function addOption(sel,value,text) {
  var i,ops;

  for (i=0;i<sel.options.length;i++) if (sel.options[i].value==value) return;
  ops=new Option();
  ops.value=value;
  ops.text=text==null?value:text;
  sel.options.add(ops);
}

function typingNumber(inp) {
  var truncated, numbers=["1","2","3","4","5","6","7","8","9","0"];

  if (!in_array(inp.value.substring(inp.value.length-1, inp.value.length), numbers)) {
    truncated=inp.value.substring(0,inp.value.length-1);
    inp.value=truncated;
  }
}

function typingDecimal(inp) {
  var truncated, numbers=[".","1","2","3","4","5","6","7","8","9","0"];

  if (!in_array(inp.value.substring(inp.value.length-1, inp.value.length), numbers)) {
    truncated=inp.value.substring(0,inp.value.length-1);
    inp.value=truncated;
  }
}

function checkYear(inp) {
  if (inp.value!="") {
    if (inp.value.length<4 || parseInt(Math.abs(inp.value))>parseInt(date.getFullYear())) {
      alert("Invalid tahun.");
      inp.select();
      inp.focus();
      return false;
    }
  }
  return true;
}

function addToFavorite(item) {
  var url = "/ajax/addtofavorite";
  var params = Object.toQueryString({item: item});
  document.getElementById("loading").style.visibility="visible";
  new Ajax(url + "?" +params, {
    method: 'get',
    onComplete: function(){
      if (trim(this.response.text)!=0) {
        var newLink="<a href=\"javascript:removeFromFavorite("+item+")\" title=\"Hapus dari favorite\" >";
          newLink=newLink+"<img src=\"images/rem_fav.gif\" width=\"12\" height=\"12\" style=\"border:0px;padding-left:2px;padding-right:2px\" ></a>";
        document.getElementById("fav_link"+item).innerHTML=newLink;
        document.getElementById("assistant").innerHTML=trim(this.response.text);
      }

      document.getElementById("loading").style.visibility="hidden";
    }
  }).request();
}

function removeFromFavorite(item) {
  var url = "/ajax/removefromfavorite";
  var params = Object.toQueryString({item: item});
  document.getElementById("loading").style.visibility="visible";
  new Ajax(url + "?" +params, {
    method: 'get',
    onComplete: function(){
      if (trim(this.response.text)!=0) {
        var newLink="<a href=\"javascript:addToFavorite("+item+")\" title=\"Simpan di favorite\" >";
          newLink=newLink+"<img src=\"images/add_fav.gif\" width=\"12\" height=\"12\" style=\"border:0px;padding-left:2px;padding-right:2px\" ></a>";
        document.getElementById("fav_link"+item).innerHTML=newLink;
        document.getElementById("assistant").innerHTML=trim(this.response.text);
      }

      document.getElementById("loading").style.visibility="hidden";
    }
  }).request();
}

function emailto(email, subject, title, width, height){
  var size="width="+width+"px,height="+height+"px";

	emailwindow=dhtmlmodal.open("EmailBox", "iframe", "/utility/mail?to="+email+"&subject="+subject, title, size+",center=1,resize=0,scrolling=1");

	emailwindow.onclose=function() {
    var to=trim(this.contentDoc.mail.to.value);
    var subject=trim(this.contentDoc.mail.subject.value);
    var message=trim(this.contentDoc.mail.message.value);
    var replyAddress=trim(this.contentDoc.mail.replyAddress.value);

    if (subject=="") {
			alert("Subject email belum diisikan.");
      this.contentDoc.mail.subject.focus();
			return false;
		}
    if (message=="") {
			alert("Isi pesan belum diisikan.");
      this.contentDoc.mail.message.focus();
			return false;
		}
    if (replyAddress=="") {
			alert("Reply address belum diisikan.");
      this.contentDoc.mail.replyAddress.focus();
			return false;
		}
    else if (replyAddress.indexOf("@")==-1 || replyAddress.indexOf(".")==-1) {
			alert("Invalid reply address.");
      this.contentDoc.mail.replyAddress.select();
      this.contentDoc.mail.replyAddress.focus();
			return false;
    }
    
    var url = "/ajax/sendmailtodealer";
    var params = Object.toQueryString({to: to, subject: subject, message: message, replyAddress: replyAddress});
    document.getElementById("loading").style.visibility="visible";
    new Ajax(url + "?" +params, {
      method: 'get',
      onComplete: function(){
        if (trim(this.response.text) != 1)
          alert("Pengiriman email gagal.");
        else
          alert("Pengiriman email success.");

        document.getElementById("loading").style.visibility="hidden";
      }
    }).request();
    
    return true;
	}
}
function confirmSendMail(result) {
  alert(result?"Email telah terkirim.":"Gagal mengirimkan email.");
}

function mailtofriend(id,view){
  var size="width=460px,height=330px";
  emailwindow=dhtmlmodal.open("EmailBox", "iframe", "/utility/mailtofriend?batchmode=1", "Email to friend", size+",center=1,resize=0,scrolling=1");

	emailwindow.onclose=function() {
    var to=trim(this.contentDoc.mail.to.value);
    var subject=trim(this.contentDoc.mail.subject.value);
    var message=trim(this.contentDoc.mail.message.value);
    var replyAddress=trim(this.contentDoc.mail.replyAddress.value);

    if (to=="") {
			alert("Email target belum diisikan.");
      this.contentDoc.mail.to.focus();
			return false;
		}
    else if (to.indexOf("@")==-1 || to.indexOf(".")==-1) {
			alert("Invalid mail address.");
      this.contentDoc.mail.to.select();
      this.contentDoc.mail.to.focus();
			return false;
    }
    if (subject=="") {
			alert("Subject email belum diisikan.");
      this.contentDoc.mail.subject.focus();
			return false;
		}
    if (message=="") {
			alert("Isi pesan belum diisikan.");
      this.contentDoc.mail.message.focus();
			return false;
		}
    if (replyAddress=="") {
			alert("Reply address belum diisikan.");
      this.contentDoc.mail.replyAddress.focus();
			return false;
		}
    else if (replyAddress.indexOf("@")==-1 || replyAddress.indexOf(".")==-1) {
			alert("Invalid reply address.");
      this.contentDoc.mail.replyAddress.select();
      this.contentDoc.mail.replyAddress.focus();
			return false;
    }
    
    var url = "/ajax/mailtofriend";
    var params = Object.toQueryString({to: to, subject: subject, message: message, replyAddress: replyAddress, id:id, view:view});
    document.getElementById("loading").style.visibility="visible";
    new Ajax(url + "?" +params, {
      method: 'get',
      onComplete: function(){
        if (trim(this.response.text) != 1)
          alert("Pengiriman email gagal.");
        else
          alert("Pengiriman email success.");

        document.getElementById("loading").style.visibility="hidden";
      }
    }).request();
    
    return true;
	}
}
