var GB_ROOT_DIR = 'http://dev2.webon.net/WO62/greybox/';

/*------------ Used in templates:  oppdater_firma, bli_kunde ----------*/
function check_company(){
    var contact     = document.company.elements['contact'].value;
    var companyname = document.company.elements['companyname'].value;
    var orgnu       = document.company.elements['orgnu'].value;
    var address     = document.company.elements['address'].value;
    var zipcode     = document.company.elements['zipcode'].value;
    var city        = document.company.elements['city'].value;
    //var telephone   = document.company.elements['telephone'].value;
    var email       = document.company.elements['from'].value;

    //-----Check for content-----
    if (!contact) {
      window.alert("Vennligst oppgi kontaktperson");
      return false;
    }
    else if (!companyname) {
      window.alert("Vennligst oppgi firmanavn");
      return false;
    }
    else if (!orgnu) {
      window.alert("Vennligst oppgi organisasjonsnummer");
      return false;
    }
    else if (!address) {
      window.alert("Vennligst oppgi adresse");
      return false;
    }
    else if (!zipcode) {
      window.alert("Vennligst oppgi postnummer");
      return false;
    }
    else if (!city) {
      window.alert("Vennligst oppgi poststed");
      return false;
    }
    else if (!email) {
      window.alert("Vennligst oppgi epostadresse");
      return false;
    }
    //else if (!telephone) {
    //  window.alert("Vennligst oppgi telefonnummer");
    //  return false;
    //}

    //-----Check for valid content-----
    if(!validate_zipcode_no(zipcode)){
      return false;
    }
    else if(!validate_email(email)){
      return false;
    }
    else if(!validate_telephone(telephone)){
      return false;
    }
    //-----Return true if everything is ok-----
    return true;
}


function check_order(){
/* ----------midlertidig deaktivert-------------
    var d_fname       = document.orders.elements['ORDERS.D_FNAME'].value;
    var d_lname       = document.orders.elements['ORDERS.D_LNAME'].value;
    var d_zipcode     = document.orders.elements['ORDERS.D_ZIPCODE'].value;
    var d_city        = document.orders.elements['ORDERS.D_CITY'].value;
    var d_email       = document.orders.elements['ORDERS.D_EMAIL'].value;
    var d_telephone   = document.orders.elements['ORDERS.D_TELEPHONE'].value;

    //-----Check for content-----
    if (!d_fname) {
      window.alert("Vennligst oppgi fornavn");
      return false;
    }
    else if (!d_lname) {
      window.alert("Vennligst oppgi etternavn");
      return false;
    }
    else if (!d_zipcode) {
      window.alert("Vennligst oppgi postnummer");
      return false;
    }
    else if (!d_city) {
      window.alert("Vennligst oppgi poststed");
      return false;
    }
    else if (!d_email) {
      window.alert("Vennligst oppgi epostadresse");
      return false;
    }
    else if (!d_telephone) {
      window.alert("Vennligst oppgi telefonnummer");
      return false;
    }

    //-----Check for valid content-----
    if(!validate_zipcode_no(d_zipcode)){
      return false;
    }
    else if(!validate_email(d_email)){
      return false;
    }
    else if(!validate_telephone(d_telephone)){
      return false;
    }
*/
    //-----Return true if everything is ok-----
    return true;
}


function validate_email(email_str){
  var email_filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

  if (!email_filter.test(email_str)){
    alert("Epostadressen er ikke gyldig: Eksempel på riktig adresse er: fornavn.etternavn@firma.no");
    return false;
  }
  else {
    return true;
  }
}

function validate_zipcode_no(zipcode_str){
  var zipcode_filter = /^([\d]+)$/i;

  if (!zipcode_filter.test(zipcode_str)){
    alert("Postnummeret kan bare inneholde tall");
    return false;
  }
  else if(zipcode_str < 1 || zipcode_str > 9999){
    alert("Postnummeret må være et tall mellom 0001 og 9999");
    return false;
  }
  else {
    return true;
  }
}

function validate_telephone(telephone_str){
  var telephone_filter = /^([\d]+)$/i;

  if (!telephone_filter.test(telephone_str)){
    alert("Telefonnummeret kan bare inneholde tall");
    return false;
  }
  else if(telephone_str < 10000000 || telephone_str > 99999999){
    alert("Telefonnummeret er ugyldig");
    return false;
  }
  else {
    return true;
  }
}

// Loop up ziparea from zipcode
// Takes 3 input parameters
// zipcode - The zipcode to look up
// languagecode - Supports several language codes, default is 'NO' or ''
// id - Id for field to display name of ziparea in
// NB! Requires Prototype to work
function ajaxzip(zipcode,languagecode,id) {
  var exturl = 'http://www.webon.net/wsp/webon_ekstranett/frontend.cgi?func=ajax_services.zipcode&debug=off'
  exturl = exturl + '&zipcode=' + zipcode + '&languagecode=' + languagecode + '&language=' + languagecode;
  var url = '/wsp/axellus/frontend.cgi?func=ajax.call&ajax_func=get_url&debug=off&url=' + encodeURIComponent(exturl); 
  var retur = "";

  new Ajax.Request(url, {
    onSuccess: function(transport) {
      var ziparea = $(id);
      if(ziparea) {
        var json = transport.responseText.evalJSON();
        if(json) {
          if(json.status == '') {
            $(ziparea).writeAttribute('value',json.ziparea);  
            retur = json.ziparea;
          }
          else {
            $(ziparea).writeAttribute('value','');  
            alert(json.status);
          }
        }
      }
    }
  });

  return retur;
}

document.observe('dom:loaded', function(){
  togglingInput();
  orderSubmit();
  tellFriend();
});

/**************** Toggle ***********************/
function togglingInput(){
 if($$('.toggle')){
     $$('.toggle').each(function(i){
         i.observe('focus', function(e){ if(this.getValue() == this.title){ this.clear(); }});
         i.observe('blur', function(e){ if(this.getValue().blank()) {this.value=this.title; }});
     });
  }
}


function orderSubmit(){
	if($('orders')){
		$('orders').observe('submit',function(e){
			var err=0;
			var errMsg= new Array();
			var f = Event.element(e);
                        
			f.select('.mandatory').each(function(o){
				var i = new ValidateFields(o);

                                var d = new Date();
                                var curr_year = d.getFullYear();

				if(o.hasClassName('email')){
                                        if(!i.isEmail() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-email'); } else{ if(i.isEmail() || o.value != o.title){o.removeClassName('invalid-email');} }
				}else if(o.hasClassName('phone')){
					if(!i.isMobile() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-phone'); } else{ if(i.isMobile() || o.value != o.title){o.removeClassName('invalid-phone');} }
				}else if(o.hasClassName('number')){
					if(!i.isNumber() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-number'); } else{ if(i.isNumber() || o.value != o.title){o.removeClassName('invalid-number');} }
				}else if(o.hasClassName('zipcode')){
					if(!i.isZipcode() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-zipcode'); } else{ if(i.isZipcode() || o.value != o.title){o.removeClassName('invalid-zipcode');} }			
				}else if(o.hasClassName('dob')){ /*** age 18+ validate ***/
					if(curr_year - o.value < 18 || i.isBlank()){ err++; errMsg.push(o.title); o.addClassName('invalid-year'); } else{ if(curr_year - o.value >= 18){o.removeClassName('invalid-year');} }			
				}else{
					if(i.isBlank() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-blank'); } else{ if(!i.isBlank() || o.value != o.title){o.removeClassName('invalid-blank');} }
				}
			});
			if(err>0){
                                Event.stop(e);
				if(!$('backdrop')){

                                        var showWarning; 
                                        var warningTxt = '<b>Følgende felter mangler:</b> ' + errMsg.join(", ");
                                        $('warning').update(warningTxt);
					//var warning = new MsgBox('<div><p>please_input_correct</p><strong>'+errMsg.join(", ")+'</strong></div>', 'warning', {'width':300,'height':120});
					/*warning.showAlert();*/
				}
			}
		});
	}
}

var ValidateFields = new Class.create({
    initialize : function(input){ 
        this.inp = input;
        this.error = 0;
        this.warningText = input.title;
        this.form = input.up('form');
        this.label = $$('label[for="'+input.id+'"]')[0];
        this.stringVal = input.getValue().toString();
        this.rules = new Array();
        this.rules['number'] = '^(\d)+\.?,?\d+$';
        this.rules['email'] = '^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$';
        this.rules['date'] = '^(\d{1,2}-\d{1,2}-\d{4})$';
    },
    ruleCheck : function(){ 
        var error = 0;
     
        if(this.inp.hasClassName('mandatory')){
           if(this.isBlank()){
             error++;
             this.showError();
           }else{
            if(this.inp.hasClassName('number') && !this.isNumber()){ error++; this.showError(); }
            else if(this.inp.hasClassName('email') && !this.isEmail()){ error++; this.showError(); }
            else if(this.inp.hasClassName('date') && !this.isDate()){  error++; this.showError(); }
           }
        }else{
           if(!this.inp.getValue().blank()){ 
               if(this.inp.hasClassName('number') && !this.isNumber()){ error++; this.showError(); }
               else if(this.inp.hasClassName('email') && !this.isEmail()){ error++; this.showError(); }
               else if(this.inp.hasClassName('date') && !this.isDate()){  error++; this.showError(); }
               else { error=error; }
           }
        }
       return error;
    },
    isBlank : function(){
        return this.stringVal.blank();
    },
    isNumber : function(){ 
     return (/(\d)+\.?,?\d+$/).test(this.stringVal);
    },
    isEmail : function(){ 
       return (/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/).test(this.stringVal)
    },
    isDate : function(){
       return (/^(\d{4}-\d{2}-\d{2})$/).test(this.stringVal);
    },
    isMobile : function(){
       /*return (/(?:^$)|(?:^(?:\+\d{2}|00\d{2})?[ ]?[1-9]{1}[0-9 ]{7,}$)/).test(this.stringVal);*/
       return (/^\d{8}$/).test(this.stringVal);
    },
    isZipcode : function(){
       return (/^\d{4}$/).test(this.stringVal);
    },
    showError : function(){
        var input = this.inp;
        var label = this.label;
        var errMsg = input.title || 'error'; 
        
       if(label){
        if(!$('error_'+input.id)){
          var msg = '<label id="error_'+input.id+'" for="'+input.id+'" class="warning">'+errMsg+'</label>';
          label.hide().insert({'after' : msg });
        }
         this.inp.observe('focus', function(event){
            if($('error_'+input.id)){ $('error_'+input.id).remove(); }
                label.show();
        });
       }
    }    
});



var popup = new Class.create({
      initialize : function(popupId, innerElem, opt){
           
            this.opt = opt;
            this.self = this;
            var s = this;
            var vp = document.viewport;
            this.innerElem = innerElem;
            this.backdrop =  new Element('div', { id : 'backdrop'}).setStyle({ 'width' : '100%',  'display' : 'none', 'background' : '#000', 'left' : '0', 'top':'0', zIndex : '998' });
            this.frame = new Element('iframe', { 'id' : 'iframe-overlay','frameborder' : 'no', 'style' : 'z-index:997;border:0 none;width:100%;left:0;top:0' });
            $(this.frame).setOpacity(0);
            $(document.body).insert({'bottom' : $(this.frame)});
            this.div = innerElem;
            this.div.setStyle({zIndex:'999'});
            this.div.id = popupId;
            this.div.addClassName('webon-popup');
            if(!$('backdrop')){ $(document.body).insert({'bottom':this.backdrop}); }
            $(this.div).observe('click', function(){ 
                s.destroy(); 
                if(searching!=null){ searching.transport.abort(); }
            });
            $('backdrop').observe('click', function(){ 
                s.destroy();
                if(searching!=null){ searching.transport.abort(); }
            });
            $(this.div).setStyle({'width' : this.opt.width+'px', 'height' : this.opt.height+'px', left : ((vp.getWidth() - this.opt.width)*0.5)+'px', 'top' : ((vp.getHeight() - this.opt.height)*0.5)+'px' });
     },
      display : function(){  
          if(!$(this.backdrop).visible()){
             new Effect.Appear('backdrop', { duration : 0.1 , to : 0.6});
             $(document.body).insert({'bottom' : $(this.div)});
           }

      },
      destroy : function(){
         if($(this.div)){ 
             $(this.frame).remove();
             $(this.div).hide();
             $(this.div).remove();  
             $('backdrop').remove();  
         }
      },
      alertBox : function(title, callback){
           var s = this.self;
           Event.stopObserving($(this.backdrop), 'click');
           Event.stopObserving($(this.div), 'click');
           $(this.div).setStyle({'overflow' : 'auto'});
           var xBtn = new Element('span').update('<img src="/axellus/frontend/css/icon/close-window-btn.gif" title="'+'close_window'+'">').setStyle({ 'cursor':'pointer','display':'block','float':'right','paddingRight' : '3px' }).observe('click', function(e){ s.destroy(); });
           var top = new Element('div').update(xBtn).setStyle({'height':'25px', 'line-height':'25px','text-align':'right','clear':'both','background':'url(/WO62/greybox/header_bg.gif) 0% repeat-x', 'borderBottom' : '1px solid #d8d8d8'});
               top.insert({'top': '<span style="float:left;padding-left:5px;color:#333333">'+title+'</span>' });
           var btn = new Element('button',{ 'id' : 'ok-btn-alertBox', 'style' : 'margin-top:10px;height:25px;'}).update('<span style="display:none">ok</span>').observe('click', function(e){ s.destroy(); if(callback && typeof(callback)=='function'){ callback();} }).wrap('p');
           this.div.insert({ 'top' : top }).insert({'bottom':btn});
           s.display();       
      },
      confirmBox : function(title, callback){
       var s = this.self;
           Event.stopObserving($(this.backdrop), 'click');
           Event.stopObserving($(this.div), 'click');
           $(this.div).setStyle({'overflow' : 'auto'});
           var xBtn = new Element('span').update('<img src="/axellus/frontend/css/icon/close-window-btn.gif" title="'+'close_window'+'">').setStyle({ 'cursor':'pointer','display':'block','float':'right','paddingRight' : '3px' }).observe('click', function(e){ s.destroy(); });
           var top = new Element('div').update(xBtn).setStyle({'height':'25px', 'line-height':'25px','text-align':'right','clear':'both','background':'url(/WO62/greybox/header_bg.gif) 0% repeat-x', 'borderBottom' : '1px solid #d8d8d8'});
               top.insert({'top': '<span style="float:left;padding-left:5px;color:#333333">'+title+'</span>' });
           var yesbtn = new Element('button',{ 'class' : 'button', 'style' : 'margin-top:10px;height:25px;'}).update('yes').observe('click', function(e){ s.destroy(); if(callback && typeof(callback.yes)=='function'){ callback.yes();} });
           var nobtn = new Element('button',{ 'class' : 'button', 'style' : 'margin-left:5px;margin-top:10px;height:25px;'}).update('no').observe('click', function(e){ s.destroy(); if(callback && typeof(callback.no)=='function'){ callback.no();} });
           var p = new Element('p').insert({'top':yesbtn}).insert({'bottom':nobtn});
           this.div.insert({ 'top' : top }).insert({'bottom':p});
           s.display();
      },
      isDisplayed : function() {
          if($('backdrop') && $('backdrop').visible()){ return true; }else{ return false; }
     }

  });
  var MsgBox = new Class.create({
      initialize : function(msg, title, opt, callback){
           this.msg = msg;
           this.title = title;
           this.callback = callback;
           this.div = new popup('alert', new Element('div').update(msg).setStyle({'background' : '#ffffff', 'border' : '4px solid #D8D8D8'}),{ 'width' : opt.width, 'height' : opt.height});
      },
      showAlert : function(){
           this.div.alertBox(this.title, this.callback);
           this.show();
      },
      show : function(){ 
           this.div.display();
           Event.stopObserving($('backdrop'), 'click');
      },
      showConfirm : function(){
           this.div.confirmBox(this.title, this.callback);
           this.show();
      }
  });

function tellFriend(){
	if($('tell_friends_form')){
		$('tell_friends_form').observe('submit',function(e){
			var err=0;
			var errMsg= new Array();
			var f = Event.element(e);
                        
			f.select('.mandatory').each(function(o){
				var i = new ValidateFields(o);

				if(o.hasClassName('email')){
                                        if(!i.isEmail() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-email'); } else{ if(i.isEmail() || o.value != o.title){o.removeClassName('invalid-email');} }
                                }else{
					if(i.isBlank() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('invalid-blank'); } else{ if(!i.isBlank() || o.value != o.title){o.removeClassName('invalid-blank');} }
				}
			});
			if(err>0){
                                Event.stop(e);
				if(!$('backdrop')){

                                        var showWarning; 
                                        var warningTxt = '<b>Følgende felter mangler:</b> ' + errMsg.join(", ");
                                        $('warning').update(warningTxt);
				}
			}
		});
	}
}