var GB_ROOT_DIR = 'http://www.webon.no/WO62/greybox/';
var searching = null;
document.observe('dom:loaded', function(){
  seminarValidate();
  if($('login-form')){
     var ajaxing = null;
       $('login-form').observe('submit', function(e){
          if($('username').getValue().blank() || $('username').getValue()==$('username').title){
            var warning = new MsgBox('login_alert', 'warning', {'width':170,'height':117}, function(){ $('username').focus(); });
            warning.showAlert();
            Event.stop(e);
          }
       });
  }
  Element.addMethods({
  cloneElement: function(element) {
    var clone = $(element).cloneNode(true);
    $(clone).select('*[id]').concat(clone).invoke('writeAttribute', { id: null });
    return clone;
  }
  });
  contactUsSubmit();
  if($('ga-contact-form')){
     $('ga-contact-form').observe('submit', function(e){
       var nextpage = this.down('#nextpage');
       var defNextPage = nextpage.getValue();
       var em = this.down('#email');
       if($('sent-msg')){ $('sent-msg').remove(); }
       Event.stop(e);  
        var err=0;
        var errMsg= new Array();
        var f = Event.element(e);
            f.select('input[type="text"], select, textarea').each(function(o){
               var i = new ValidateFields(o);
               if(o.id == 'epost'){
                  if(!i.isEmail()){ err++; errMsg.push(o.title); }
               }
               else if(o.id == 'telephone'){
                  if(!i.isNumber()){  err++; errMsg.push(o.title); }
               }
               else{
                  if(i.isBlank()){  err++; errMsg.push(o.title); }
               }
            });
         if(err>0){
            if(!$('backdrop')){
            var warning = new MsgBox('<div><p>please_input_correct</p><strong>'+errMsg.join(", ")+'</strong></div>', 'warning', {'width':300,'height':117});
            warning.showAlert();
            }
         }else{ 
           nextpage.value = 'func=frontend.show&template=inc_contact_form&ajax=yes&sentmail=sent';
           var preload = new popup('preloader', new Element('div', { 'style' : 'background:url(http://www7.webon.net/webon_ekstranett/frontend/css/loadingAnimation.gif) 50% no-repeat;color:#ffffff;font-weight:bold'}).update('loading'),{'width':'300','height':'100'});
           f.insert({'bottom' : '<input id="ajax" name="ajax" type="hidden" value="yes">'});
           preload.display();
           ajaxIFrameLoad(f, function(result){ nextpage.value =  defNextPage; f.insert({'bottom':result});f.reset(); preload.destroy();$("ajax").remove(); });
         }     
     });
  }
  if($('search')){
     var f = $('search'); 
     f.observe('submit', function(e){
          if($('search_name').getValue().blank() || $('search_name').getValue().strip() == $('search_name').title){ 
             
              var warning = new MsgBox('search_alert', 'warning', {'width':150,'height':100}, function(){ $('search_name').focus(); });
              warning.showAlert();
              Event.stop(e);
          }
     });
     $('search_name').observe('keypress', function(e){ 
               if($('backdrop')){
                  $('backdrop').remove();
                  $('preloader').remove();
                  $('iframe-overlay').remove();
               }
          /*     if($('target')){ 
                  $('target').remove(); 
                  $('ajax').remove();
                  $('collage').remove();
                } */
            if(searching != null){ searching.transport.abort(); }
     });
     $('search_name').observe('keyup', function(e){
        if($('preloader')){ $('preloader').remove(); if($('iframe-overlay')){$('iframe-overlay').remove();} }
        if(!this.getValue().blank() && this.getValue().strip().length>2){ 
             var s = this;
             var output = !$('search_result') ? $('bd') : $('search_result');
             var collage = !$('search_result') ? 'yes' : 'no';
         //    f.insert({'bottom' : '<input id="ajax" name="ajax" type="hidden" value="yes"><input type="hidden" id="collage" name="collage" value="'+collage+'">'});
             var preload = new popup('preloader', new Element('div', { 'style' : 'background:url(http://www7.webon.net/webon_ekstranett/frontend/css/loadingAnimation.gif) 50% no-repeat;color:#ffffff;font-weight:bold'}).update('loading'),{'width':'300','height':'100'});;
       //      preload.display();
          //   ajaxIFrameLoad(f, function(result){ output.update(result);preload.destroy();$("ajax").remove(); $('collage').remove()});
               searching = new Ajax.Request(f.action+'&ajax=yes&collage='+collage+'&search_name='+escape(s.getValue()), {
                 method : 'get',
                 onCreate: function(){  preload.display(); },
                 onComplete : function(r){ preload.destroy(); if(r.responseText.strip() != ''){ output.update(r.responseText);  }  } 
                });
            // Google Analytics search tracking
            var searchstring = '/searchresult?search='+s.getValue();
            pageTracker._trackPageview(searchstring);
        }        
     });
  }
  togglingInput();
});
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 ajaxIFrameLoad(f, callback){
         var iframe = new Element('iframe', { 'id' : 'target', 'name' : 'target', 'src' : 'about:blank', 'style' : 'display:none' });
           f.insert({'after' : iframe});
           f.setAttribute('target', 'target');
           f.submit();
           new PeriodicalExecuter(function(pe) { 
                var result = iframeLoaded('target');
                if(!result.blank()){
                   pe.stop();
                   callback(result);
                   if($('target')){ $('target').remove(); }
                 }
           }, 3);
}
function iframeLoaded(id){
        var i = $(id);
        if(i.contentDocument) {
           var d = i.contentDocument;
        }else if (i.contentWindow) {
            var d = i.contentWindow.document;
        }else {
            var d = window.frames[id].document;
        } 
        if(d.body && !d.body.innerHTML.blank()) {
            return d.body.innerHTML;
        }else{
            return '';
        }
}
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="/wo_internett/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="/wo_internett/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 seminarValidate(){
	if($('seminar')){
		$('seminar').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); }
				}else if(o.hasClassName('mobile')){
					if(!i.isMobile() || o.value == o.title){ err++; errMsg.push(o.title); }
				}else{
					if(i.isBlank() || o.value == o.title){ err++; errMsg.push(o.title); }
				}
			});
			if(err>0){
                                Event.stop(e);
				if(!$('backdrop')){
					var warning = new MsgBox('<div><p>please_input_correct</p><strong>'+errMsg.join(", ")+'</strong></div>', 'warning', {'width':300,'height':120});
					warning.showAlert();
				}
			}
		});
	}
}

function tellFriendSubmit(){
  if($('tell_friend_form')){
      Event.stopObserving($('tell_friend_form'), 'submit');
      $('tell_friend_form').observe('submit', function(e){
           Event.stop(e);
           var f = this;
           var err = 0;
           errMsg = new Array();
           var inp = f.select('input[type="text"], [disabled!="disabled"], select, textarea');
               inp.each(function(o){
                  var i = new ValidateFields(o);
                  if(o.id == 'email'){
                       if(!i.isEmail() || o.value == o.title){ err++; errMsg.push(o.title); }
                  }else{
                     if(i.isBlank() || o.value == o.title){  err++; errMsg.push(o.title); }
                  } 
               });
           if(err<1){
                 f.insert({'bottom':'<input type="hidden" id="ajax" name="ajax" value="yes">'});
                 f.hide();
                 ajaxIFrameLoad(f, function(result){ $('tip_friend').update(result); });               
                 $('tip_friend').insert({'top' : '<p><strong>loading</strong><br><img src="/wo_internett/frontend/graphics/loadingAnimation.gif"></p>'}); 
           }else{
                var warning = new MsgBox('<p>please_input_correct</p><strong>'+(errMsg.join(', ')).gsub(':','')+'</strong>', 'warning', {'width':320,'height':140});
                warning.showAlert();
           }
        });
    }
}
function captcha_reload()
{
    var url = '/wsp/wo_internett/frontend.cgi?template=captcha_code';
    new Ajax.Request(url, {
       onComplete: function(resp) {
            var captcha_code = resp.responseText.evalJSON();
            $('recaptcha_image').src='/wo_internett/authen_captcha/'+captcha_code.code+'.png';
            $('captcha_code').value = captcha_code.code;
       }
     });
}
function contactUsSubmit(){
 if($('contact-us-form')){  
  $('contact-us-form').observe('submit', function(e){
       if(this.down('#nextpage')){
       var nextpage = this.down('#nextpage');
       var defNextPage = nextpage.getValue();
       }
       var em = this.down('#email');
       if($('sent-msg')){ $('sent-msg').remove(); }
       Event.stop(e);  
        var err=0;
        var errMsg= new Array();
        var f = Event.element(e);
            f.select('input[type="text"], select, textarea').each(function(o){
               var i = new ValidateFields(o);
               if(o.id == 'epost' || o.id == 'email'){ 
                  if(!i.isEmail() || o.value == o.title){ err++; errMsg.push(o.title); o.addClassName('error'); $('epost-error').setStyle({'display':'block'}); } else{ if(i.isEmail() || o.value != o.title){o.removeClassName('error'); $('epost-error').setStyle({'display':'none'});} }
               }else{
                  if(i.isBlank() || o.value == o.title){  err++; errMsg.push(o.title); }
               }
            });
         if(err>0){
            if(!$('backdrop')){
            var warning = new MsgBox('<div><p>please_input_correct</p><strong>'+errMsg.join(", ")+'</strong></div>', 'warning', {'width':300,'height':135});
            warning.showAlert();
            }
         }else{ 
          this.getElements().each(function(i){
            if(i.id != 'recaptcha_response_field'){
              i.value = iso2utf8(i.getValue());
            }
          }); 
          var preload = new popup('preloader', new Element('div', { 'style' : 'background:url(http://www7.webon.net/webon_ekstranett/frontend/css/loadingAnimation.gif) 50% no-repeat;color:#ffffff;font-weight:bold'}).update('loading'),{'width':'300','height':'100'});
          f.request({
             parameters: { 'ajax':'yes', 'debug':'off' },
             onLoading: function(){ preload.display(); },
             onSuccess: function(result){
              f.insert({'bottom': result.responseText});  
              preload.destroy(); 
              f.reset();
              //Recaptcha.reload();
              captcha_reload();
             }             
          });
           if(nextpage){   nextpage.value = 'func=frontend.show&template=inc_contact_form&ajax=yes&sentmail=sent'; }
         }     
     });
 }
}
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);
    },
    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();
        });
       }
    }    
});
function imagesRotation(){
   if($$('a[rel="front-banner"]').length > 0){
   //var url = '/wsp/wo_internett/frontend.cgi?func=frontend.show&template=banner_rotation_ajax';
   var l = location;
   var url = l.protocol+'//'+l.hostname+'/wsp/wo_internett/frontend.cgi?template=banner_rotation_ajax&debug=off';
   var div = $('teaser');
   var defaultDuration = 6.5;
   if(div){  div.setStyle({ "height":div.getHeight()+"px", "overflow":"hidden" }); }
   new Ajax.Request(url, {
       onComplete: function(r){
            var j = r.responseText.evalJSON();
                j.each(function(obj){
                  var p = new Element('p', { "duration" : obj.DURATION}).addClassName("rotation-image").hide();
                  var a = new Element('a', { "rel": "front-banner", "title": obj.TXT, "href": obj.URL }).addClassName("rotation-image");
                  a.update('<img src="/wo_internett'+obj.IMG+'" alt="'+obj.TXT+'">');
                  if(obj.BTN != ''){
                    var btn = new Element('a', {'rel': 'button-link', 'href':obj.BTN.LINK, 'title': obj.BTN.TXT}).addClassName(obj.BTN.CLASSNAME).update('<img src="'+obj.BTN.SRC+'" alt="'+obj.BTN.TXT+'">');
                    p.insert({bottom:btn});  
                  }
                  p.insert({bottom:a});
                  $('teaser').insert({bottom:p});
                 });
        var i=0;
        if(j.length>0){
       new PeriodicalExecuter(function(pe){
           var a = $$('p.rotation-image');
           var duration = Math.round((parseFloat(isNaN(a[0].readAttribute("duration")) ? 0 : a[0].readAttribute("duration")) / 10)*10) > 0 ? parseFloat(a[0].readAttribute("duration")) : defaultDuration;
           if(!a[0]){ pe.stop(); }
            i++;
            var btnLink = a[0].previous('a[rel="button-link"]');
            if(i==0){ if(btnLink){  btnLink.show(); } $(a[0]).appear(); }
            if(i == (duration * 10)-10){
               if(btnLink){  btnLink.remove(); }
               (a[0]).fade();
            }
            if (i==(duration * 10)){
              var clone = $(a[0]).cloneNode(true);
              $(clone).select('*[id]').concat(clone).invoke('writeAttribute', { id: null });
              var img = clone;
              $('teaser').insert({bottom:img.hide()});
              $(a[0]).remove();
              i=-1;
            }
        },0.1);
        }
       }
   });
}
}
function iso2utf8(str) {
  replaceStr = [{"char":"æ", "replacement":"&aelig;"},{"char":"ø", "replacement":"&oslash;"},{"char":"å", "replacement":"&aring;"},{"char":"Æ", "replacement":"&AElig;"},{"char":"Ø", "replacement":"&Oslash;"},{"char":"Å", "replacement":"&Aring;"}];
  replaceStr.each(function(s){
    str = str.gsub(new RegExp(s.char), s.replacement);
  });
  return str;
}
window.onload=function(){   imagesRotation(); }
/************************Add parameter to search url*************************/
/*function add_param() {
  var search = document.getElementById('search_name').value;
  var action = document.searchform.action; 
  document.searchform.action = action + '&s=' + search;
  return true;
}
*/
/************************ End of add_param *************************/

