var unmarked = new Image();
var illegal = new Image();
var marked = new Image();
var highlighted = new Image();
var marked_highlight = new Image();

var unmarked = new Image();
var illegal = new Image();
var marked = new Image();
var highlighted = new Image();
var marked_highlight = new Image();

function h(d,b,c)
{
  if (b == 1) { if (c == 1) d.src="http://static.adoperator.com/webshop.gif"; else d.src="http://static.adoperator.com/webshop.gif"; }
  if (b == 2) { if (c == 1) d.src="http://static.adoperator.com/key.gif"; else d.src="http://static.adoperator.com/key.gif"; }
}

function Hover(d,over)
{
     var doc = getElement(d);
     if (doc != null)
     	{
	  if (d == 'top_menu_login_img')         {  if (over) doc.src = "http://static.adoperator.com/topmenu_loggain.gif";    else doc.src = "http://static.adoperator.com/topmenu_loggain-over.gif";    }
	  else if (d == 'top_menu_logout_img')   {  if (over) doc.src = "http://static.adoperator.com/topmenu_loggaut.gif";    else doc.src = "http://static.adoperator.com/topmenu_loggaut-over.gif";    }
	  else if (d == 'top_menu_account_img')  {  if (over) doc.src = "http://static.adoperator.com/topmenu_mittkonto.gif";  else doc.src = "http://static.adoperator.com/topmenu_mittkonto-over.gif";  }
     	  else if (d == 'top_menu_help_img')     {  if (over) doc.src = "http://static.adoperator.com/topmenu_hjalp.gif";      else doc.src = "http://static.adoperator.com/topmenu_hjalp-over.gif";      }
	  else if (d == 'menu_home_img')         {  if (over) doc.src = "http://static.adoperator.com/menu-hem.jpg";           else doc.src = "http://static.adoperator.com/menu-hem-over.jpg";    	}
	  else if (d == 'menu_buy_img')          {  if (over) doc.src = "http://static.adoperator.com/menu-kop.gif";           else doc.src = "http://static.adoperator.com/menu-kop-over.gif";    	}
	  else if (d == 'menu_sell_img')         {  if (over) doc.src = "http://static.adoperator.com/menu-salj.gif";          else doc.src = "http://static.adoperator.com/menu-salj-over.gif";    	}
	  else if (d == 'menu_search_img')       {  if (over) doc.src = "http://static.adoperator.com/menu-leta.gif";          else doc.src = "http://static.adoperator.com/menu-leta-over.gif";    	}
  	  else if (d == 'top_menu_contact_img')  {  if (over) doc.src = "http://static.adoperator.com/topmenu_kontakt.gif";    else doc.src = "http://static.adoperator.com/topmenu_kontakt-over.gif";   }
       }
}

function dayover(d)
{
  if (selecting && pressing && d.src != illegal.src)
  {
    mark(d,1);
    d.src = marked_highlight.src;
  }
  else if (d.src == unmarked.src)
    d.src = highlighted.src;
  else if (d.src == marked.src)
    d.src = marked_highlight.src;
  else if (d.src != illegal.src)
   alert("An error occured, please contact support@adoperator.com");
}

function dayout(d)
{
 if (selecting && pressing && d.src != illegal.src)
 {
    d.src = marked.src;
    mark(d,1);
    }
 else if (d.src == highlighted.src)
   d.src = unmarked.src;
 else if (d.src == marked_highlight.src)
   d.src = marked.src;
}

function mark(e,c)
{
  var b=getElement(e.id.substr(4));
 if (b != null)
   {
     if (b.value != c)
      {
       if (c == 0)
        num_marked--;
       else
        num_marked++;
       
       b.value=c;
       b=getElement("ab_count");
       b.innerHTML = num_marked;
       b=getElement("ab_cost");
       var l=num_marked*cost_per_day*100.0;
       l = Math.ceil(l) / 100.0;
       b.innerHTML = "" + l + " kr";
     }
  }
}

function moveHandler(e)
{
 if (e == null) {e = window.event;}
 if (e.button == 0 && dragOk) 
   {
     mouseUp(e);
     return false;
   }
}

function mouseUp(e)
{
 document.onmousemove=old_onmousemove;
}

function dragHandler(e)
{
 if (e == null) {e = window.event;}
 var target = e.target != null ? e.target : e.srcElement;
 if (target) {
 if ((target.src==unmarked.src ||
     target.src==highlighted.src) && highlighted.src && unmarked.src)
   {
     selecting = true;
     pressing = true;
     target.src=marked_highlight.src;
     mark(target,1);
     document.onmousemove=moveHandler;
     old_onmousemove=document.onmousemove;
     return false;
   }
 else if ((target.src==marked.src ||
          target.src==marked_highlight.src) && highlighted.src && unmarked.src)
   {
     if (pressing && selecting)
       {
         pressing = false;
         selecting = false;
       }
      else
      {
       target.src=unmarked.src;
       mark(target,0);
       }
     return false;
   }}
 if (pressing && selecting)
 {
   pressing=false;
   selecting=false;
   mouseUp(e);
 }
 if (old_onmousedown)
   return old_onmousedown(e);
 return true;
}

var pressing = false;
var selecting = false;
var old_onmousedown=document.onmousedown;
var old_onmousemove=document.onmousemove;
document.onmousedown=dragHandler;
var savedTarget = null;
var dragOk = false;

function getElement(id) {
	 if (document.getElementById)
	    return document.getElementById(id);
	 else if (document.all)
	    return document.all[id];
	 else
	    return document.layers[id];
}
function gE(id) {
	 if (document.getElementById)
	    return document.getElementById(id);
	 else if (document.all)
	    return document.all[id];
	 else
	    return document.layers[id];
}

function saveScroll()
{
getElement("sx").value = (document.all) ? document.body.scrollLeft : window.pageXOffset;
getElement("sy").value = (document.all) ? document.body.scrollTop : window.pageYOffset;
return true;
}
function debug(p){var s='';for(j in p){s+=j+'='+p[j]+'\n';}alert(s);}
function visitScroll(url)
{
  var sx = (document.all) ? document.body.scrollLeft : window.pageXOffset;
  var sy = (document.all) ? document.body.scrollTop : window.pageYOffset;
  document.location.href = url + "&sx=" + sx + "&sy=" + sy;
}

var speed_y = 0;
var scroll_num = 0;

function restoreScroll() {
   var x = (document.all) ? document.body.scrollLeft : window.pageXOffset;
   var y = (document.all) ? document.body.scrollTop : window.pageYOffset;
   
   if (speed_y == 0)
    speed_y = (savedScrollY-y) / 8;
   if (savedScrollY > y && savedScrollX > x)
     window.scrollBy(30,speed_y);
   else if (savedScrollX > x)
     window.scrollBy(30,0);
   else if (savedScrollY > y)
     window.scrollBy(0,speed_y);
   else {
     window.scrollTo(savedScrollX,savedScrollY);
     return;
   }
   scroll_num++;
   if (scroll_num > 10)
     {       
   	window.scrollTo(savedScrollX,savedScrollY);
	return;
     }
  setTimeout('restoreScroll()',50);
}

function Preview() {
        var f = getElement('preview');
	var text_color = getElement('foreground_colour');
	var bg_color = getElement('background_colour');
	var num_ads = getElement('number_ads');
	var direction = getElement('ad_dir');
	var adid = getElement("ad_id_preview");
	var ad_width = getElement("ad_width");
	var ad_height = getElement("ad_height");
	var allowsText = getElement("allows_text");
	var allowsFlash = getElement("allows_flash");
	var allowsImage = getElement("allows_image");
	var use_adv = getElement("use_adv");
	var end = "";

	if (use_adv && use_adv.value == 'true') {
          text_color = getElement("adv_text_title").value + "," + getElement("adv_text_txt").value + "," + getElement("adv_text_lnk").value + "," + getElement("adv_text_adop").value;
	  ad_width = getElement("adv_width");
	  ad_height = getElement("adv_height");
	  bg_color = getElement("adv_block_bg");
	  var title_bar_bg_color = getElement("adv_adop_bg");
	  num_ads = getElement("adv_num");
	  var trnsp = getElement("adv_block_trnsp");
	  var ttl_trnsp = getElement("adv_adop_trnsp");
	  var configString = getElement("adv_configstring");
	  direction = getElement("adv_dir");
	  var size = getElement("size_text_adv");
	  var config = configString.value;
	  if (trnsp.checked)
	    config += ",blk_trnsp";
          if (ttl_trnsp.checked)
	    config += ",ado_trnsp";

	  if(getElement("adv_und_adop").checked) config += ",und_ado";
	  if(getElement("adv_und_title").checked) config += ",und_title";
	  if(getElement("adv_und_txt").checked) config += ",und_txt";
	  if(getElement("adv_und_lnk").checked) config += ",und_lnk";

	  if (getElement("adv_wgt_ado_b").checked)
	    config += ",wgt_ado=700";
	  if (getElement("adv_wgt_ado_n").checked)
	    config += ",wgt_ado=400";
	  if (getElement("adv_wgt_ado_t").checked)
	    config += ",wgt_ado=100";

	  if (getElement("adv_wgt_title_b").checked)
	    config += ",wgt_title=700";
	  if (getElement("adv_wgt_title_n").checked)
	    config += ",wgt_title=400";
	  if (getElement("adv_wgt_title_t").checked)
	    config += ",wgt_title=100";

	  if (getElement("adv_wgt_txt_b").checked)
	    config += ",wgt_txt=700";
	  if (getElement("adv_wgt_txt_n").checked)
	    config += ",wgt_txt=400";
	  if (getElement("adv_wgt_txt_t").checked)
	    config += ",wgt_txt=100";
	    
	  if (getElement("adv_wgt_lnk_b").checked)
	    config += ",wgt_lnk=700";
	  if (getElement("adv_wgt_lnk_n").checked)
	    config += ",wgt_lnk=400";
	  if (getElement("adv_wgt_lnk_t").checked)
	    config += ",wgt_lnk=100";

	  try {
	    var temp = size.innerHTML.split('x');
	    if (temp[0] && temp[0] > 0)
  	      f.style.width=temp[0] + "px";
	    temp = temp[1].split('p');
   	    temp = temp[0].split(' ');
	    if (temp[0] && temp[0] > 0)
	      f.style.height=temp[0] + "px";
	  }catch(err){}
	  
	  f.src = "preview.jsp?allowsText=true&ad_width=" + ad_width.value + "&ad_height=" + ad_height.value + "&textColour=" + text_color + "&bgColour=" + bg_color.value + "&ttlBgColour=" + title_bar_bg_color.value + "&numAds=" + num_ads.value + "&configString=" + escape(config) + "&direction=" + direction.value + end;
	} else {
	 if (num_ads == null) num_ads = getElement('number_ads_hid');
	 if (direction == null) direction = getElement('ad_dir_hid');

	 if (!f) alert("Could not find preview");
	 if (ad_width && ad_height) {
	   f.style.width=ad_width.value + "px";
	   f.style.height=ad_height.value + "px";
	 } else {
	   f.style.width=getWidth() + "px";
	   f.style.height=getHeight() + "px";
	 }

	 if (adid) end = "&adid=" + adid.value;
	 if (ad_width) end = end + "&ad_width="+ad_width.value;
	 if (ad_height) end = end + "&ad_height="+ad_height.value;
	 if (allowsText) end = end + "&allowsText";
	 if (allowsImage) end = end + "&allowsImage";
	 if (allowsFlash) end = end + "&allowsFlash";
	 f.src = "preview.jsp?textColour=" + text_color.value + "&bgColour=" + bg_color.value + "&numAds=" + num_ads.value + "&direction=" + direction.value + end;
        }
}

var glob_x = 0; //global helper vars
var glob_y = 0;
function getPos(o){x=0;y=0;while(o){x+=o.offsetLeft;y+=o.offsetTop;o=o.offsetParent||null}return{x:x,y:y}}
function getXY(d_o)
{
    glob_x = 0;
    glob_y = 0;
    while(d_o)
	{
 		glob_x += d_o.offsetLeft;
		glob_y += d_o.offsetTop;
		d_o = d_o.offsetParent || null;
	}
}

function clickBuyTab(d)
{
  var div_0 = getElement('textSettings');
  var div_1 = getElement('bannerSettings');
  var div_2 = getElement('textStandard');
  var div_3 = getElement('textAdvanced');
  var tab_0 = getElement('tabText');
  var tab_1 = getElement('tabBanner');
  var tab_2 = getElement('tabTextStd');
  var tab_3 = getElement('tabTextAdv');
  var useAdv= getElement('use_adv');
  if (d == 0) {
    tab_0.className = 'active';
    div_0.style.display='block';
    tab_1.className = 'inactive';
    div_1.style.display='none';
    getElement('preview').style.display='block';
  } else if (d == 1) {
    tab_0.className = 'inactive';
    div_0.style.display='none';
    tab_1.className = 'active';
    div_1.style.display='block';
    getElement('preview').style.display='none';
  } else if (d == 2) {
    tab_2.className = 'active';
    tab_3.className = 'inactive';
    div_2.style.display='block';
    div_3.style.display='none';
    useAdv.value = 'false';
    getElement('preview').style.display='block';
    Preview();
  } else if (d == 3) {
    tab_2.className = 'inactive';
    tab_3.className = 'active';
    div_2.style.display='none';
    div_3.style.display='block';
    useAdv.value = 'true';
    getElement('preview').style.display='block';
    a_l();
  }
}

function checkboxChange(e,n){var ne=getElement(n);if(e.checked)ne.checked=true;else ne.checked=false;}
function newBannerSize(e){var d=getElement(e.id+"_div");if(d){if(e.checked)d.style.display='block';else d.style.display='none';}}

function integerFormat(amount)
{
 var i = parseFloat(amount);
 if(isNaN(i)) { i = 0.00; }
 var neg = '';
 if(i<0) neg='-';
 i=Math.abs(i);
 i=parseInt(i*100);
 i=i/100;
 s=new String(i);
 if(s.indexOf('.') < 0) { s += '.00'; }
 if(s.indexOf('.') == (s.length - 2)) { s+='0'; }
 s=neg+s;
 var delimiter = " ";
 var a=s.split('.',2)
 i=parseInt(a[0]);
 if(isNaN(i)) { return ''; }
 i=Math.abs(i);
 var n=new String(i);
 var a=[];
 while(n.length > 3){
  var nn = n.substr(n.length-3);
  a.unshift(nn);
  n=n.substr(0,n.length-3);
 }
 if(n.length>0)a.unshift(n);
 n=a.join(delimiter);
 s=neg+n;
 return s;
}

function currFormat(amount)
{
 var i = parseFloat(amount);
 if(isNaN(i)) { i = 0.00; }
 var neg = '';
 if(i<0) neg='-';
 i=Math.abs(i);
 i=parseInt(i*100);
 i=i/100;
 s=new String(i);
 if(s.indexOf('.') < 0) { s += '.00'; }
 if(s.indexOf('.') == (s.length - 2)) { s+='0'; }
 s=neg+s;
 var delimiter = " ";
 var a=s.split('.',2)
 var d = a[1];
 i=parseInt(a[0]);
 if(isNaN(i)) { return ''; }
 i=Math.abs(i);
 var n=new String(i);
 var a=[];
 while(n.length > 3){
  var nn = n.substr(n.length-3);
  a.unshift(nn);
  n=n.substr(0,n.length-3);
 }
 if(n.length>0)a.unshift(n);
 n=a.join(delimiter);
 if(d.length<1)s=n;
 else s=n+','+d;
 s=neg+s;
 return s;
}

function SETI2(e,o,t) {
var b=gE(o);
if(b&&e){b.value=e.value;if(b.selectedIndex==-1)b.selectedIndex=0;else SUTI(e.value,t);}
}
function SETI(e,o,t)
{
if(e)SUTI(e.value,t);
else if(o)SUTI(o.value,t);
var b=gE(o);
if(b&&e){if(e.value=="-1")b.value="ID";else b.value=e.value;}
}
function SUTI(v,t)
{
new Ajax.Request('jx/aIB.jsp', {
	        method:'post',
	        requestHeaders: {Accept: 'application/json'},
		parameters: {"ad":v},
		onSuccess: function(transport,json){
		      var b=gE(t);
		      if (json.status=="ok") {
			if(b){b.onmouseover=function(){Tip(transport.responseText);};}
		      }else if (json.status=="noselect") {
		        if(b){b.onmouseover=function(){Tip('You can either select your ad directly using the dropdown menu<br/>or you can enter the id of the ad in the input field to the left.');};}
		      }else{
		        if(b){b.onmouseover=function(){Tip('<b>An error occured when trying to show ad information</b>');};}
		      }
		 },
		 onFailure: function(transport){
		  var b=gE(t);
		  if(b){b.onmouseover=function(){Tip('<b>An error occured when trying to show ad information</b>');};}
		 }
	         });
}
function IODINE(page,includeList,id,fname,lname,email,company,url,campaign,res,onUser,onObject,success,failure){
var g,u,f,i,l,e,c;var fo=gE(fname);if(fo)f=fo.value;var io=gE(id);
if(io)i=io.value;var lo=gE(lname);if(lo)l=lo.value;var eo=gE(email);
if(eo)e=eo.value;var b=gE(res);var co=gE(company);if(co)c=co.value;
if(b)b.innerHTML="<img src=\"working.gif\" border=\"0\" alt=\"Loading\"/>";
g=gE(campaign);if(g)g=g.value;u=gE(url);if(u)u=u.value;
if(!success)success=function(transport,json){
if(b){b.innerHTML=transport.responseText;}}
if(!failure)failure=function(t){if(b)b.innerHTML='<font class="error">An error occured while trying to search for a user</font>';}
new Ajax.Request(page,{
	        method:'post',
	        requestHeaders:{Accept:'application/json'},
		parameters: {"id":i,"email":e,"fname":f,"lname":l,"company":c,"url":u,"campaign":g,"include":includeList,"onUser":onUser,"onObject":onObject},
		onSuccess:success,
		onFailure:failure});
}

function grow(e)
{
var b=gE(e);
if(b)
     {
       if(b.style.visibility=='visible')
	  {b.ado_dir=-(b.ado_desired_height/15);}
      else
      	  {b.ado_dir=(b.ado_desired_height/15);showDiv(e);
     	   b.style.height="1px";b.ado_curr_height=1;}
	   b.style.overflow="hidden";
growS(b);}
}
function growS(b){setTimeout(function(){if(growG(b)==1)growS(b);else if(b.ado_dir<0)hideDivO(b);},50);}
function growG(b){if(b.ado_dir>0&&b.ado_curr_height>b.ado_desired_height||(b.ado_dir<0&&b.ado_curr_height<=0)){b.style.overflow="auto";b.style.height="auto";return 0;}else{b.ado_curr_height+=b.ado_dir;b.style.height=((b.ado_curr_height<0)?1:b.ado_curr_height)+"px";return 1;}}

function hideDivO(b){if(b){b.style.visibility="hidden";b.style.display="none";}}
function hideDiv(id){var b=gE(id);if(b){b.style.visibility="hidden";b.style.display="none";}}
function showDiv(id){var b=gE(id);if(b){b.style.visibility="visible";b.style.display="block";}}
function showHideDiv(id){var b=gE(id);if(b){if(b.style.visibility!='hidden'){hideDiv(id);}else{showDiv(id);}}}

var digits="1234567890";
var money="-1234567890.";
var restrict_date="-1234567890";
function restrict(o,e){var w="";var i;for(i=0;i<o.value.length;i++){var x=o.value.charAt(i);if(e.indexOf(x,0)!=-1)w+=x;}if(o.value!=w)o.value=w;}
function isDigit(e){if(digitString.indexOf(e)!=-1)return true;return false;}
function gK(e){e=(e)?e:event;var k;if(window.event)k=e.keyCode;if(e.which)k=e.which;return k;}
function oD(e){var k=gK(e);return isDigit(String.fromCharCode(k));}
function eC(e){
 hideDiv('edr_'+e);
 showDiv('ede_'+e);
}
function eD(e,l,f){
 var g=gE('edr_'+l);
 var o=gE(e);
 if(o&&g){if(f&&g.innerHTML!=o.value)f();g.innerHTML=o.value;}
 hideDiv('ede_'+e);
 showDiv('edr_'+e);
}
function wOC(t,f){if(gK(t)==13)f();}
function fC(t,e,l)
{
if(gK(t)==13)eD(e,l);
}
function optionClear(l){
for(x=l.length;x>=0;x--){
l[x]=null;}}
function optionAdd(l,v,t){
l[l.length]=new Option(t,v);}

function setCaretPositionO(iy,o){
var elem=gE(iy);
if(elem!=null){if(elem.createTextRange){var range=elem.createTextRange();
range.move('character',o);range.select();}else{if(elem.selectionStart){
elem.focus();elem.setSelectionRange(o,o);}else elem.focus();}}}

function setCaretPositionO(elem,o){
if(elem!=null){if(elem.createTextRange){var range=elem.createTextRange();
range.move('character',o);range.select();}else{if(elem.selectionStart){
elem.focus();elem.setSelectionRange(o,o);}else elem.focus();}}}

function moveToEnd(iy){
var e=gE(iy);if(e)setCaretPositionO(e,e.value.length);
}

function moveToEndO(e){
if(e)setCaretPositionO(e,e.value.length);
}

function pickSlotTimer(o,id,slot,to)
{
 jQuery.ajax({url:'jx/gHS.jsp',
              data:{'id':gE(id).value,
	            'pick-slot':'',
		    'read':''},
	      dataType:'json',
	      success:function(json){
	        if (json.status=='0'){
		 if (json.slot!='-1') {
		   var t=gE(to);t.value=json.slot;
		   t.onchange();
		   return;
		 }
	         setTimeout(function(){pickSlotTimer(o,id,slot,to);},5000);
	        }
	      }
 });
}

function pickSlot(o,id,slot,to){
 o.href="jx/gHS.jsp?id="+gE(id).value+"&pick-slot&redirect";
 setTimeout(function(){pickSlotTimer(o,id,slot,to);},5000);
}

// ADOperator jQuery Plugins

function dateString(date) {
    var d  = date.getDate();
    var day = (d < 10) ? '0' + d : d;
    var m = date.getMonth() + 1;
    var month = (m < 10) ? '0' + m : m;
    var yy = date.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;
    return year+'-'+month+'-'+day;
}

// getAdInfo
(function($){

  $.fn.showAdInfo = function(ad,options) {
    return this.each(function(){
      p = $(this);
      p.html('');
      var opts = $.extend({}, $.fn.getAdInfo.defaults, options);
      $('<img class="pinl" src="pin.gif"/><img class="pinr" src="pin.gif"/>').appendTo(p);
      var table=$('<table></table>').appendTo(p);
      $('<tr><th>Campaign:</th><td>'+ad.campaign+'</td></tr>').appendTo(table);
      $('<tr><th>Balance:</th><td>'+ad.balance+' SEK</td></tr>').appendTo(table);
      $('<tr><th>'+ad.paymentModel+':</th><td>'+ad.paymentPrice+' SEK</td></tr>').appendTo(table);
      $('<tr><th>Type:</th><td>'+ad.type+'</td></tr>').appendTo(table);
      $('<tr class="frequency"><th>Frequency:</th><td><span>'+ad.frequency+'%</span> <a class="frequency" href="javascript:void(0)">edit</a></td></tr>').appendTo(table);
      $('<tr><th>Disabled:</th><td>'+ad.disabled+'</td></tr>').appendTo(table);
      $('<tr><th>Geolocation:</th><td>'+ad.geolocation+'</td></tr>').appendTo(table);
      $('<input type="text" size="3" value="'+ad.frequency+'" name="frequency"/><').appendTo(table.find('tr.frequency td')).hide();
      $('<input type="button" value="Save"/><').appendTo(table.find('tr.frequency td')).hide();
      table.find('tr.frequency input[type=button]').click(function(){
          $.ajax({url:opts.url,dataType:'json',data:{ad:ad.id,frequency:table.find('tr.frequency input[type=text]').val(),action:'changeFrequency'},
	          success:function(json){
		      if(json.status=='0'){
		         table.find('tr.frequency td span').html(json.ad.frequency+'%');
		         table.find('tr.frequency td span,tr.frequency td a').show();
			 table.find('tr.frequency td input').hide();
			 opts.frequencyChangeCallback(json);
		      }else alert('Error occured: '+json.error);
		  },
		  error:function(a,b,c){alert(a+","+b+","+c);}
	  });
      });
      table.find('a.frequency').click(function(){
	   table.find('tr.frequency td span,tr.frequency td a').hide();
	   table.find('tr.frequency td input').show();
      });
    });
  };
  
  $.fn.getAdInfo = function(options) {
    return this.each(function(){
      $this = $(this);
      var opts = $.extend({}, $.fn.getAdInfo.defaults, options);
      $this.click(function(){
        var p=$(opts.placeholder).html('Loading Ad Information...');
	opts.classes.each(function(o){$this.addClass(o);});
        $.ajax({url:opts.url,dataType:'json',data:{ad:opts.id},
	       success:function(json) {
	         if(json.status!='0'){alert('Error occurred: '+json.error);return;}
	         p.showAdInfo(json.ad,options);
	       }
	});
      });
    });
  };
  
  $.fn.getAdInfo.defaults = {
    classes: ['adInfo'],
    url: 'jx/aI.jsp',
    placeholder: 'div#adInfo',
    frequencyChangeCallback: function(json){}
  }

  $.fn.showInvoiceInfo = function(invoice,options) {
    var $this=$(this);
    $this.html('');
    var d=new Date(invoice.date*1000);
    $('<div class="id">#'+invoice.id+'</div>').appendTo($this);
    $('<div class="date">'+dateString(d)+'</div>').appendTo($this);
    var table=$('<table></table>').appendTo($this);
    if(invoice.customer) {
      $('<tr><th>Reference:</th><td>'+invoice.customer.reference.name+'</td></tr>').appendTo(table);
      $('<tr><th>Company:</th><td>'+invoice.customer.company+'</td></tr>').appendTo(table);
      $('<tr><th>Address:</th><td>'+invoice.customer.address+'</td></tr>').appendTo(table);
    }
    $('<tr><th>Our reference:</th><td>'+invoice.reference.name+'</td></tr>').appendTo(table);
    $('<tr><th>Order:</th><td>#'+invoice.order+'</td></tr>').appendTo(table);
    $('<tr><th>Sum:</th><td>'+invoice.sum+' SEK</td></tr>').appendTo(table);
    $('<tr><th>Vat:</th><td>'+invoice.vat+' SEK</td></tr>').appendTo(table);
    $('<tr><th>Grand Total:</th><td>'+invoice.grandTotal+' SEK</td></tr>').appendTo(table);
    $('<tr><td><a href="Pdf?view='+invoice.id+'&approved" target="_blank">View PDF</a></td></tr>').appendTo(table);
  };

  function getUserLink(id) {
    return "<a href='javascript:void(0)' class='loadUser'>#"+id+"</a>";
  }

  function userIsLoaded(user) {
    if (!user) return false;
    if (user.name || user.firstname)
     return true;
    return false;
  }

  $.fn.showOrderInfo = function(order,options) {
    var $this=$(this);
    $this.html('');
    var d=new Date(order.date*1000);
    var opts = $.extend({deep:true}, $.fn.showOrderInfo.defaults, options);
    if (!opts.adInfoOptions)
     opts.adInfoOptions = $.extend({}, $.fn.getAdInfo.defaults, undefined);

    $('<div class="id">#'+order.id+'</div>').appendTo($this);
    $('<div class="date">'+dateString(d)+'</div>').appendTo($this);
    var table=$('<table></table>').appendTo($this);
    if(userIsLoaded(order.owner)) {
      $('<tr><th>Buyer:</th><td>'+order.owner.firstname+' '+order.owner.lastname+'</td></tr>').appendTo(table);
      $('<tr><th>Company:</th><td>'+order.owner.company+'</td></tr>').appendTo(table);
      $('<tr><th>Address:</th><td>'+order.owner.address+'</td></tr>').appendTo(table);
    } else
      $('<tr><th>Buyer:</th><td>'+getUserLink(order.owner.id)+'</td></tr>').appendTo(table);

    if(userIsLoaded(order.adopReference)) {
      $('<tr><th>Salesperson:</th><td>'+order.adopReference.firstname+' '+order.adopReference.lastname+'</td></tr>').appendTo(table);
      $('<tr><th>Company:</th><td>'+order.adopReference.company+'</td></tr>').appendTo(table);
      $('<tr><th>Address:</th><td>'+order.adopReference.address+'</td></tr>').appendTo(table);
    } else if (order.adopReference)
      $('<tr><th>Salesperson:</th><td>'+getUserLink(order.adopReference.id)+'</td></tr>').appendTo(table);

    for(var i=0;i<order.items.length;i++) {
      $('<tr><th>Item #'+(i+1)+'</th><td>'+order.items[i].string + '</td></tr>').appendTo(table);
      var j=$('<tr><th></th><td><a href="javascript:void(0)">Annons ('+order.items[i].ad.id + ')</a></td></tr>').appendTo(table);
      j.find('a').click(showOrderInfo_adClick(order.items[i].ad,opts.adInfoOptions));
    }
    $('<tr><th>Sum:</th><td>'+order.sum+' SEK</td></tr>').appendTo(table);
  };

  function showOrderInfo_adClick(ad,options) {
    return function() {
      $(options.placeholder).showAdInfo(ad,options);
    }
  }
  
  function dateTimeString(date) {
    var d  = date.getDate();
    var day = (d < 10) ? '0' + d : d;
    var m = date.getMonth() + 1;
    var month = (m < 10) ? '0' + m : m;
    var yy = date.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;
    var h=date.getHours();
    var hour=(h<10)?'0'+h:h;
    var m=date.getMinutes();
    var minute=(m<10)?'0'+m:m;
    var s=date.getSeconds();
    var second=(s<10)?'0'+s:s;
    return year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
  }

  $.fn.getInvoiceInfo = function(options) {
    return this.each(function(){
      $this = $(this);
      var opts = $.extend({}, $.fn.getAdInfo.defaults, options);
      $this.click(function(){
        var p=$(opts.placeholder).html('Loading Ad Information...');
	opts.classes.each(function(o){$this.addClass(o);});
        $.ajax({url:opts.url,dataType:'json',data:{ad:opts.id},
	       success:function(json) {
if(json.status!='0'){alert('Error occurred: '+json.error);return;}
	       }
	});
      });
    });
  };
  
  $.fn.showOrderInfo.defaults = {
    classes: ['orderInfo'],
    url: 'jx/inv.jsp',
    placeholder: 'div#orderInfo',
    adInfoOptions: undefined      // undefined means copy information from $.fn.getAdInfo.defaults
  }
  
  $.fn.showInvoiceInfo.defaults = {
    classes: ['invoiceInfo'],
    url: 'jx/inv.jsp',
    placeholder: 'div#invInfo'
  }

 function fillInMessage(p,message) {
   p.find('span.text').html(message.text.replace(/\n/g,'<br/>'));
   p.find('span.date').text(dateTimeString(new Date(message.date*1000)));
   p.find('span.name').html('<a href="mailto:'+message.author.email+'" title="Skicka email">'+message.author.firstname+' '+message.author.lastname+'</a>');
 }

 var messageCache;

 function addMessage(window,message) {
//   debug(message);
   var p=$('<div id="message'+message.id+'"></div>').appendTo(window);
   if (messageCache) {
     m = messageCache.clone();
     m.appendTo(p);
     fillInMessage(m,message);
     window.find('div.message').each(function(n,o){
       if ((n%2)==0) {$(o).addClass('second');}
     });
   } else {
     p.load('x_message.jsp',undefined,function(){
       fillInMessage(p,message);
       window.find('div.message').each(function(n,o){
         if ((n%2)==0) {$(o).addClass('second');}
       });
     });
   }
 }

 function popupWindow(where,options) {
   var p=where;
   return function() {
       var m=$('div#messageBox');
       var pos=getPos(p.context);
       if(m.length==0) {
         m=$('<div id="messageBox">Loading...</div>').appendTo('div#main_container');
	 m.hide();
	 m.css({ top:pos.y+"px",left:pos.x+"px"});
	 m.show('fast');
       } else {
         m.hide('fast',function(){m.css({ top:pos.y+"px",left:pos.x+"px"});m.show('fast');});
       }
       m.load('x_message_head.jsp',undefined,function(){
	 $.ajax({url:'x_message.jsp',dataType:'html',success:function(E,L){
	  messageCache=$(E);
          var write=m.find('table');
	  var title=(typeof options.title=='function')?options.title(options):options.title;
          write.find('td.thread').text(title);
          m.find('div.title').html(title);
	  if (options.messages) $.each(options.messages,function(n,o){addMessage(m, o);});
          write.find('td.post input').click(function(){
	   $.ajax({url:'jx/message.jsp?action=add',
	   	   data:{type:options.type,id:options.id,user:options.user.id,message:write.find('textarea').val()},
		   dataType:'json', success:function(json){
		     if(json.status=='ok') {
		       write.find('textarea').val('');
		       m.find('div.write').hide();
		       addMessage(m, json.message);
		       if (!options.messages) options.messages=new Array();
		       options.messages.push(json.message);
		       p.find('span').html(options.messages.length);
		     } else debug(json);
		   }});
	  });
	 }});
   });
 }
 }
 function retrieveTitle(options) {
   var title=options.titles[options.type+'_'+options.id];
   if (!title) title=options.titles['default'];
   if (!title) title="$id$ref";
   title=title.replace(/\$id/g,options.id).replace(/\$ref/g,options.type);
   return title;
 }

 $.fn.attachManyMessages = function(options) {
    var split=jQuery.fn.getMessages.splitIntoRef(options.messages);
    return this.each(function(n,o){
      var t=$(o);
      var classes = t.attr('class').split(' ');
      var ref='';
      var user='';
      for(i=0;i<classes.length;i++) {
       if(classes[i].match('^ref_'))
	  ref=classes[i].substr(4);
       else if(classes[i].match('^user_'))
          user=classes[i].substr(5);
      }
      var s=ref.split('_');
      if(!user)user=options.user;else user={id:user,name:'Not set'};
      var title;
      if(typeof options.titles!="function") title=retrieveTitle; else title=options.titles;
      var opt = $.extend({}, options, {id:s[1],type:s[0],title:title,user:user});
      var length=split[ref];
      if(length) length=length.length; else length='';
      opt.messages=split[ref];
      t.attachMessages(opt).find('span').html( length );
    });
 }

 $.fn.attachMessages = function(options) {
   this.each(function(n,o,v){
     p = $(o);
     p.bind('click', popupWindow(p,options));
     });
   return this;
 }
 
 $.fn.getMessages = function(options) {
   var cache = {};
   this.each(function(){
     p = $(this);
   });

   return this;
 }

 $.fn.getMessages.splitIntoRef = function(messages) {
   var s={};
   for(i=0;i<messages.length;i++) {
     var m=messages[i];
     var ref=m.reference.type;
     if (m.reference.id>0) ref+="_"+m.reference.id;
     if (!s[ref]) {s[ref]=new Array();}
     s[ref].push(m);
   }
   return s;
 }
})(jQuery);

function attachOwner(users,id) {
  jQuery(users).each(function(n,o){
    if (o.id==id) return o;
  });
  return {id:id};
}

var progressBar = undefined;

function jxModuleCaller_append_object(c,json,settings,clear) {
     if (clear) jQuery('#'+c.attachTo).html('');
     jQuery(c.resultInformation).each(function(nn,info){
       if (json.ads && info.type=='ads') {
          if (!info.alreadyAdded) {
	    if (info.outerFunction)
	      info.alreadyAdded=info.outerFunction(info,jQuery('#'+c.attachTo),json);
	     else
	      info.alreadyAdded=jQuery(info.outer).appendTo('#'+c.attachTo);
	  }
          jQuery(json.ads).each(function(n,o){
           o.owner=attachOwner(json.users,o.id);
	   var r=info.row;
	   var actions_left=currFormat((o.balance/o.paymentPrice));
	   r=r.replace(/\$ad.id/g,o.id).replace(/\$ad.campaign/g,o.campaign).replace(/\$ad.actions_left/g,actions_left).
	       replace(/\$ad.balance/g,currFormat(o.balance)).replace(/\$ad.company/g,o.owner.company).
	       replace(/\$ad.globalFrequency/g,o.frequency+"%").replace(/\$ad.disabled/g,o.disabled).
	       replace(/\$ad.dopeLevel/g,o.dopeLevel);
	   if (info.rowFunction)
	     info.rowFunction(info,info.alreadyAdded,r,json);
	   else
	     jQuery(r).appendTo(info.alreadyAdded);
          });
       } else if (info.type=='progress' && json.progress) {
         if (progressBar) {
	   progressBar.remove();
	 }
         var q=jQuery(info.outer).appendTo('div#main_container div.inner').hide();
	 q.find('.close').hide().click(function(){q.hide()});
	 progressBar = q;
       	 q.fadeIn(400);
         jxModuleCaller_progress_process(c,settings,json,info,json);
      	 jxModuleCaller_progress(c,settings,json,info);
       }
     });
}

function jxModuleCaller_build(c,json) {
 var g=jQuery('#'+c.prefix+'od');
 var ac=jQuery('<div class="jxModule" id="'+c.prefix+json.action+'">Action: '+json.action+'</div>').appendTo(g);
 jQuery('<input class="param" type="hidden" name="action" value="'+json.action+'"/>"').appendTo(ac);
 jQuery('<pre>'+json.help.description+'</pre>').appendTo(ac);
 var table=jQuery('<table></table>').appendTo(ac);
 jQuery(json.help.params).each(function(n,j){
  var p=c.prefix+json.action+j.param;
  var i='';
  if (j.values) {
    i='<select class="param" name="'+j.param+'">';
    for(var o=0;o<j.values.length;o++) {
     i+='<option value="'+j.values[o].value+'"';
     if (j.values[o].value==j.defaultValue) i+=' selected';
     i+='>'+((j.values[o].name)?j.values[o].name:j.values[o].value)+'</option>';
    }
    i+='</select>';
  } else {
    i='<input class="param" type="text" id="'+p+'" name="'+j.param+'" value="'+j.defaultValue+'"/>';
  }
  var k = jQuery('<tr id="'+p+'"><td class="c1">'+j.param+'</td><td class="c2">'+i+'</td><td class="c3">'+j.description+'</td></tr>').appendTo(table);
 });
 var res=jQuery('#'+c.attachTo);
 jQuery('<input type="button" value="Submit"/>').appendTo(jQuery('<td class="c1"></td>').appendTo( jQuery('<tr><td class="c2"></td></tr>').appendTo(table))).click(function(){
   jQuery.ajax({url:c.path,dataType:'json',data:jQuery('div#'+c.prefix+json.action+' .param').serialize(),success:function(jsonR){
     if (jsonR.error) debug(jsonR);
     jxModuleCaller_append_object(c,jsonR,json,true);
   }});
 });
}

function jxModuleCaller_progress_process(c,settings,progressJson,info,j) {
    var to=jQuery('#'+info.attachTo);
    var maxWidth=to.find('.bar').width();
    to.find('span.action').html(j.progress.currentAction);
    to.find('.content').width(maxWidth * j.progress.percentage);
    to.find('.percentage').html(Math.round(j.progress.percentage*100)+'%');
    var log=to.find('.log');
    jQuery(j.progress.events).each(function(n,o){
      if (o.event) log.append('<span class="'+o.type+'">'+o.event+'</span><br/>');
      if (o.object) jxModuleCaller_append_object(c,o.object,settings,false);
    });
    log.animate({ scrollTop: log.attr("scrollHeight") }, 1000);
    if (!j.progress.halted) {
      var jj=jQuery.extend({},j,{});
      jj.progress = undefined; /* prevent endless recursion */
      setTimeout(function(){jxModuleCaller_progress(c,settings,j,info)}, 600);
    } else if (j.progress.success) {
      to.fadeOut(2000,function(){
        try {$(this).remove();}catch(err){}
      });
      jQuery(c.resultInformation).each(function(n,info){
       info.alreadyAdded = undefined;
      });
    } else {to.find('.close').show();}
}

function jxModuleCaller_progress(c,settings,progressJson,info) {
  jQuery.ajax({url:"progress.jx",dataType:'json',data:{action:'progress',progress:progressJson.progress.id},success:function(j){
     jxModuleCaller_progress_process(c,settings,progressJson,info,j);
  }});
}

function jxModuleCaller(c) { //path,json,prefix) {
//jQuery('#'+prefix+'od').text('List of params: ' + json.help.params);
jxModuleCaller_build(c, c.json);

//  jQuery(prefix+'od').text(json);
}


(function($) {
  $.fn.verticalScroll = function(o) {
   o = $.extend({
     initialDelay: 3000,
     speed: 200,
     deltaY: 1,
     currY: 0,
     nextY: -1,
     lastObject: undefined
   }, o || {});
   return this.each(function() {
     var div=$(this),ul=div.find('ul'),elems=ul.find('li');
     elems.css({overflow:'hidden',float:'none'});
     ul.css({position:'relative', float:'left','list-style-type':'none','z-index':'1'});
     setTimeout(function() {
       o.nextY = -elems.height();
       o.lastObject = $(elems[elems.length-1]);
       setInterval(function() {
         var p=ul.position();
	 o.currY-=o.deltaY;
	 var i=Math.round(o.currY);
	 if (i < o.nextY - 10) {
	   o.currY = -10;
	   var k=$(o.lastObject);
	   var j=$(elems[0]);
	   o.lastObject = j.clone();
	   o.lastObject.appendTo(ul);
	   o.currY += parseInt(j.css('margin-bottom')) + parseInt(j.css('padding-bottom'));
	   j.remove();
	   elems=ul.find('li');
	   o.nextY = -elems.height() - parseInt(elems.css('margin-top')) - parseInt(elems.css('margin-bottom'));
	   o.lastObject = j;
	   o.currY += parseInt(elems.css('margin-top')) + parseInt(elems.css('padding-top'));
	   ul.css({top:o.currY});
	 } else if(i!=p.top)
           ul.css({top:i});
//	 $('span.kuk').html('css top = ' + p.top + ", o.nextY = " + o.nextY +  ", margin-top: " + elems.css('margin-top') + ", margin-bottom: " + elems.css('margin-bottom') + ",last_object = " + o.lastObject);
       },o.speed);
     },o.initialDelay);
   });
  }
})(jQuery);
