var AdsysMain = Class.create();
AdsysMain.prototype = {
  initialize: function() {
  },
  
  evalJSON: function(json) {
    try {
      return json ? eval('(' + json + ')') : null;
    } catch (e) {
      return null;
    }
  },
  
  handle404: function() {
    var errors = new Array();
    errors[0] = new Array(2);
    errors[0][0] = 'Error';
    errors[0][1] = 'Server returns status 404 Page Not Find';
    this.showErrors(errors);
    Element.hide('loading');
    Element.show('main_zone');
  },

  handle500: function() {
    var errors = new Array();
    errors[0] = new Array(2);
    errors[0][0] = 'Error';
    errors[0][1] = 'Server returns status 500 Server Internal Error';
    this.showErrors(errors);
    Element.hide('loading');
    Element.show('main_zone');
  },
  
  handleTimeOut: function(json)  {
    if (json != null && json['timeout']) {
      alert('Session Timeout');
      document.location = window.location;
      return true;
    }
    return false;
  },
  
  refreshList: function(url, target) {
    new Ajax.Request(url, {
      method:'get',
      asynchronous:true,
      evalScripts:true,
      on404:function(request, json){admin.handle404();},
      on500:function(request, json){admin.handle500();},
      onLoading:function(request, json){admin.handleLoading(target, ' ');},
      onSuccess:function(request, json){admin.handleListSuccess(request, json, ' ', target);}
    });
  },
  
  handleListSuccess: function(request, json, loading_div_id, target) {
    //default value for loading div id
    loading_div_id = loading_div_id || 'loading';
    if (target == undefined) target = 'list';
    
    if (this.handleTimeOut(json)) return;
    hasError = false;
    if (json != null) {
      if (json['errors']) {
        this.showErrors(json['errors']);
        hasError = true;
      } else if (json['notice']) {
        this.clearErrors();
        this.showNotice(json['notice']);
      }
    }
    if (! hasError) { Element.update(target, request.responseText); }
    
    if (loading_div_id != ' ')
      Element.hide(loading_div_id);
    
    // fix webkit layout problem
    if (Prototype.Browser.WebKit) $(target).show().setOpacity(1);
    
    new Effect.Opacity(target, { from: 0.5, to: 1.0, duration: 0.2 });
  },
  
  handleLoading: function(id, loading_div_id) {
    //default value for loading div id
    loading_div_id = loading_div_id || 'loading';
    
    if (loading_div_id != ' ') {
      Element.hide(id);
      Element.show(loading_div_id);
    }
    else {
      Effect.Fade(id, {from: 0.5, to: 0.5, duration: 0.1});
    }
  },
  
  handleCancel: function() {
    this.handleNewCancel();
    this.handleEditCancel();
    this.handleViewCancel();
    this.removeNaviLastNode();
  },
  
  clearNaviPath: function() {
    if ($('navi_path')) {
      $('navi_path').update('');
    }
  },
  
  addNaviPath: function(span_name, text, link) {
    if (! $(span_name)) {
      var new_span = document.createElement('span');
      Element.extend(new_span);
      Element.update(new_span, ' <a href="'+link+'" class="navi">&raquo; '+text+'</a> ');
      new_span.setAttribute('id', span_name);
      
      $('navi_path').appendChild(new_span);
    } else {
      var siblings = $(span_name).nextSiblings();
      for (var i = siblings.length - 1; i >= 0; i--) {
        siblings[i].remove();
      }
    }
  },
  
  addNaviTextPath: function(span_name, text) {
    if (! $(span_name)) {
      var new_span = document.createElement('span');
      Element.extend(new_span);
      Element.update(new_span, ' <span class="navi_text">&raquo; ' + text + '</span>');
      new_span.setAttribute('id', span_name);
      
      if (! $('navi_path').childElements().last().select('.navi').first()) {
        $('navi_path').childElements().last().remove();
      }
      
      $('navi_path').appendChild(new_span);
    } else {
      var siblings = $(span_name).nextSiblings();
      for (var i = siblings.length - 1; i >= 0; i--) {
        siblings[i].remove();
      }
    }
  },
  
  updateNaviPath: function(span_name, text, link) {
    if ($(span_name)) {
      $(span_name).update(' <a href="'+link+'" class="navi">&raquo; '+text+'</a>');
    }
  },
  
  updateNaviPathScript: function(span_name, text, link) {
    if ($(span_name)) {
      $(span_name).update(' <a href="#" class="navi" onclick="'+link+'; return false;">&raquo; '+text+'</a>');
    }
  },
  
  updateNaviLastNode: function() {
    var navi_path = $('navi_path');
    var last_node = navi_path.childElements().last();
    
    if (last_node) {
      var second_last_node = last_node.previous();
      
      if (second_last_node) {
        var second_last_node_title_span = second_last_node.select('.navi_text').first();
        if (second_last_node_title_span) {
          var second_last_node_link = second_last_node.select('.navi').first();
          var second_last_node_title = second_last_node_title_span.innerHTML;
          
          second_last_node_link.innerHTML = second_last_node_title;
          second_last_node_title_span.remove();
        }
      }
      var last_node_link = last_node.select('.navi').first();
      
      if (last_node_link) {
        var last_node_title = last_node_link.innerHTML;
        
        last_node_link.innerHTML = '';
        last_node.insert('<span class="navi_text">' + last_node_title + '</span>');
      }
    }
  },
  
  updateNaviNode: function(node_id, node_title) {
    var node = $(node_id);
    
    if (node) {
      var navi_text = node.select('.navi_text').first();
      if (navi_text) {
        navi_text.innerHTML = node_title;
      } else {
        node.select('.navi').first().innerHTML = node_title;
      }
    }
  },
  
  removeNaviLastNode: function() {
    var navi_path = $('navi_path');
    var last_node = navi_path.childElements().last();
    
    if (last_node) {
      var second_last_node = last_node.previous();
      
      if (second_last_node) {
        var second_last_node_link = second_last_node.select('.navi').first();
        if (second_last_node_link) {
          var second_last_node_title = second_last_node_link.innerHTML;
          
          second_last_node_link.innerHTML = '';
          second_last_node.insert('<span class="navi_text">' + second_last_node_title + '</span>');
        }
      }
      
      last_node.remove();
    }
  },
  
  updateZone: function(request, json, zone_id, loading_div_id) {
    if (this.handleTimeOut(json)) return;
    if ($(zone_id)) {
      //default value for loading div id
      loading_div_id = loading_div_id || 'loading';
      
      Element.update(zone_id, request.responseText);
      if (loading_div_id != ' ') {
        Element.hide(loading_div_id);
      }
      Element.show(zone_id);
    }
  },
  
  ajaxUpdateZone: function(url, zone_id, update_loading) {
    this.clearErrors();
    update_loading = update_loading || false;
    new Ajax.Request(url, {
      method:'get',
      asynchronous:true,
      evalScripts:true,
      on404:function(request, json){admin.handle404();},
      on500:function(request, json){admin.handle500();},
      onLoading:function(request, json){
        if (update_loading) {
          if ($(zone_id)) { $(zone_id).update('<div class="loading"/>'); }
        } else {
          admin.handleLoading(zone_id);
        }
      },
      onSuccess:function(request, json){admin.updateZone(request, json, zone_id);}
    });
  },
  
  clearErrors: function(error_box_div_id) {
    error_box_div_id = error_box_div_id || 'error_box';
    if ($(error_box_div_id)) {
      $(error_box_div_id).hide();
      if ($(error_box_div_id).down('ul')) {
        $(error_box_div_id).down('ul').update('');
      }
    }
  },
  
  showErrors: function(errors, error_box_div_id) {
    error_box_div_id = error_box_div_id || 'error_box';
    
    this.clearErrors(error_box_div_id);
    if ($(error_box_div_id)) {
      if ($(error_box_div_id).down('ul')) {
        if (Object.isArray(errors)) {
          for (var i = 0; i < errors.length; i++) {
            if (Object.isArray(errors[i])) {
              var errorLine = new Element('li').update('<strong>'+errors[i][0]+':</strong> '+errors[i][1]);
            } else {
              var errorLine = new Element('li').update(errors[i]);
            }
            
            $(error_box_div_id).down('ul').appendChild(errorLine);
          }
        } else {
          var errorLine = new Element('li').update(errors);
          $(error_box_div_id).down('ul').appendChild(errorLine);
        }
        
        var is_scrollto_error_box = false;
        Effect.Appear(error_box_div_id, {
          duration: 0.2,
          afterUpdate: function() {
            if (!is_scrollto_error_box) {
              $(error_box_div_id).scrollTo();
              is_scrollto_error_box = true;
            }
          }
        });
      }
    }
  },
  
  showNotice: function(notice) {
    if ($('notice_box')) {
      Element.update('notice', notice);
      Effect.Appear('notice_box', { duration: 0.2 });
    }

    if (this.autoHideNoticeTimer) {
      clearTimeout(this.autoHideNoticeTimer);
    }
    this.autoHideNoticeTimer=setTimeout("if ($('notice_box')) Effect.Fade('notice_box', { duration: 0.2 });", 5000);
  },
  
  hideNotice: function() {
    if ($('notice_box')) {
      Effect.Fade('notice_box', { duration: 0.2 });
    }
  },
  
  handleUpdateLoading: function(id, form_id) {
    this.clearErrors();
    if (id != undefined) {
      Effect.Fade(id, {from: 0.5, to: 0.5, duration: 0.1});
    }
    if ((form_id != undefined) && $(form_id)) {
      $(form_id).down('.form_controls_zone .form_controls').select('input').each(
        function(n) { n.disable(); }
      );
      $(form_id).down('.form_controls_zone .form_loading').show();
      $(form_id).down('.form_controls_zone .form_controls').hide();
    }
  },
  
  handleUpdateSuccess: function(json, refreshItems, form_id) {
    if (this.handleTimeOut(json)) return;
    Element.hide('loading');
    if (json['errors']) {
      this.showErrors(json['errors']);
    } else if (json['notice']) {
      this.clearErrors();
      this.showNotice(json['notice']);
      this.handleCancel();
      
      if (refreshItems == undefined) {
        this.refreshList(this.listURL, 'list');
      } else {
        if (Object.isArray(refreshItems)) {
          for (i = 0; i < refreshItems.length; i++) {
            this.refreshList(refreshItems[i].url, refreshItems[i].target);
          }
        } else {
          this.refreshList(refreshItems.url, refreshItems.target);
        }
      }
    }
    
    if ((form_id != undefined) && $(form_id)) {
      $(form_id).down('.form_controls_zone .form_controls').select('input').each(
        function(n) { n.enable(); }
      );
      $(form_id).down('.form_controls_zone .form_controls').show();
      $(form_id).down('.form_controls_zone .form_loading').hide();
    }
  },
  
  handleUpdateModSuccess: function(json) {
    if (this.handleTimeOut(json)) return;
    Element.hide('loading');
    if (json['errors']) {
      this.showErrors(json['errors']);
    } else if (json['notice']) {
      this.clearErrors();
      this.showNotice(json['notice']);
    }
  },
  
  handleUpdateListSuccess: function(json, refreshItems) {
    if (this.handleTimeOut(json)) return;
    Element.hide('loading');
    if (json['errors']) {
      this.showErrors(json['errors']);
    } else if (json['notice']) {
      this.clearErrors();
      this.showNotice(json['notice']);
      
      if (refreshItems == undefined) {
        this.refreshList(this.listURL, 'list');
      } else {
        if (Object.isArray(refreshItems)) {
          for (i = 0; i < refreshItems.length; i++) {
            this.refreshList(refreshItems[i].url, refreshItems[i].target);
          }
        } else {
          this.refreshList(refreshItems.url, refreshItems.target);
        }
      }
    }
  },
  
  handleUpdateListTdSuccess: function(request, json, td) {
    if (this.handleTimeOut(json)) return;
    
    if (json['errors']) {
      this.showErrors(json['errors']);
    } else if (json['notice']) {
      td = $(td);
      if (td) {
        Element.update(td, request.responseText);
      }
      this.clearErrors();
      this.showNotice(json['notice']);
    }
  },
  
  handleActiveSuccess: function(request, json) {
    if (this.handleTimeOut(json)) return;
    
    if (json['errors']) {
      this.showErrors(json['errors']);
    } else {
      this.clearErrors();
      if (json['id'] !== undefined) {
        var id = 'act_' + json['id'];
        
        if ($(id)) {
          Element.update(id, request.responseText);
        }
      }
      if (json['notice']) {
        this.clearErrors();
        this.showNotice(json['notice']);
      }
    }
  },
  
  handleDismissMessageSuccess: function(request, json) {
    if (this.handleTimeOut(json)) return;
    if (json['id']) {
      var id = 'msg_alert_' + json['id'];
      
      if ($(id)) {
        $(id).hide();
        $(id).nextSiblings().each(function(n) {
          n.toggleClassName('even_row');
          n.toggleClassName('odd_row');
        });
        
        // Hide alert section when no alerts
        var visible = false;
        $('alerts').select('tbody').first().childElements().each(function(n) {
          if (n.visible()) {
            visible = true;
          }
        });
        if (! visible) {
          $('alerts').hide();
        }
      }
    }
    if (json['notice']) {
      this.clearErrors();
      this.showNotice(json['notice']);
    }
  },
  
  handleRefreshUserInfoSuccess: function(request, json) {
    if (this.handleTimeOut(json)) return;
    if ($('show_user_id')) {
      Element.update('show_user_id', request.responseText);
    }
  },
  
  handleListShow: function(request, json, loading_div_id, target) {
    //default value for loading div id
    loading_div_id = loading_div_id || 'loading';
    if (target == undefined) target = 'list';
    
    if (this.handleTimeOut(json)) return;
    if ($(target)) {
      Element.update(target, request.responseText);
      
      if (loading_div_id != ' ')
        Element.hide(loading_div_id);
      
      // fix webkit layout problem
      if (Prototype.Browser.WebKit) $(target).show().setOpacity(1);
      
      new Effect.Opacity(target, { from: 0.5, to: 1.0, duration: 0.2 });
    }
  },
  
  handleNewShow: function(span_name, text) {
    if ($('main_zone')) {
      Element.hide('main_zone');
    }
    if ($('new_zone')) {
      Element.show('new_zone');
      this.addNaviTextPath(span_name, text);
      this.updateNaviLastNode();
    }
  },
  
  handleNewCancel: function() {
    this.clearErrors();
    if ($('new_zone')) {
      Element.hide('new_zone');
      if ($('id_newForm')) {
        Form.reset('id_newForm');
      }
    }
    if ($('main_zone')) {
      Element.show('main_zone');
    }
  },
  
  handleEditShow: function(request, json) {
    if (this.handleTimeOut(json)) return;
    if ($('edit_zone')) {
      Element.update('edit_zone', request.responseText);
      Element.hide('loading');
      Element.show('edit_zone');
    }
  },
  
  handleEditCancel: function() {
    this.clearErrors();
    if ($('edit_zone')) {
      Element.hide('edit_zone');
      $('edit_zone').update('');
    }
    if ($('main_zone')) {
      Element.show('main_zone');
    }
  },
  
  handleViewShow: function(request, json) {
    if (this.handleTimeOut(json)) return;
    if ($('view_zone')) {
      Element.update('view_zone', request.responseText);
      Element.hide('loading');
      Element.show('view_zone');
    }
  },
  
  handleViewCancel: function() {
    if ($('view_zone')) {
      Element.hide('view_zone');
      $('view_zone').update('');
    }
    if ($('main_zone')) {
      Element.show('main_zone');
    }
  },
  
  handleContinue: function(json, refreshTarget) {
    json_raw=json;
    json=admin.evalJSON(json);
    if(!json){alert('There is problem in processing the request'); return;}
    var f=$('id_newForm');
    if(json['test']=='pass'||json['test']=='allpass'){
      s=Form.Element.getValue('setup_step');
      if($('step'+ ++s)){
        $('setup_step').value=s;
        if($('step'+(s-1)))
          $('step'+(s-1)).hide();
        $('step'+s).show();
      }
      if(json['test']=='allpass'){
        admin.handleReview(json['fields']);
      }
    }else if(json['test']=='saved'){
      admin.handleStep(1);
      admin.completeCallback(json_raw, refreshTarget);
    }else{
      Element.hide('loading');
      admin.showErrors(json['errors']);
    }
  },
  
  handleStep: function(s){
    if($('step'+s)){
      if(s<Form.Element.getValue('setup_step')){
        var siblings=$('step'+s).siblings();
        for(var i=1; i<=siblings.length; i++){
          siblings[i-1].hide();
        }
        $('setup_step').value=s;
        admin.clearErrors();
        $('step'+s).show();
      }
    }
  },
  
  handleBack: function(r) {
    var f=$('id_newForm');
    s=Form.Element.getValue('setup_step');
    if($('step'+s)){
      if($('step'+(s-1)))
        $('step'+(s-1)).show();
      $('step'+s).hide();
      $('setup_step').value=--s;
      admin.clearErrors();
      if(s>=r) admin.handleBack(r);
    }
  },
  
  htmlDecode: function(s) {
        var str = new String(s);
        str = str.replace(/&amp;/g, "&;");
        str = str.replace(/&lt;/g, "<");
        str = str.replace(/&gt;/g, ">");
        str = str.replace(/&quot;/g, '"');
        //str = str.replace(/&#039;/g, "'");
        return str;
  },
  
  handleReview: function(json){
    $('target_location_review').innerHTML=json['target_location'];
    $('start_date_review').innerHTML=json['start_date'];
    $('end_date_review').innerHTML=json['end_date'];
    $('ad_title_review').innerHTML=json['ad_title'];
    $('payout_review').innerHTML='$ '+json['payout'];
    $('publisher_payout_review').innerHTML='$ '+json['publisher_payout'];
    $('charge_type_review').innerHTML=json['charge_type'];
    $('remark_review').innerHTML=this.htmlDecode(json['remark']);
    $('description_review').innerHTML=this.htmlDecode(json['description']);
    $('ad_type_review').innerHTML=json['ad_type'];
    if(json['ad_type_value'] == 'email'){
      $('email_from_box').style.display='block';
      $('email_from_review').innerHTML=json['email_from'];
      $('email_subject_box').style.display='block';
      $('email_subject_review').innerHTML=this.htmlDecode(json['email_subject']);
    }else{
      $('email_from_box').style.display='none';
      $('email_from_review').innerHTML='';
      $('email_subject_box').style.display='none';
      $('email_subject_review').innerHTML='';
    }
    $('email_from_review').innerHTML=json['email_from'];
    $('target_url_review').innerHTML=json['target_url'];
    //$('preview_review').innerHTML=$(json['preview_element']).innerHTML;
    if(json['allow_email_promotion'] == 1){
      $('opt_out_url_review').innerHTML=json['opt_out_url'];
      $('opt_out_address_review').innerHTML=this.htmlDecode(json['opt_out_address']);
      $('suppression_url_review').innerHTML=json['suppression_url'];
    }else{
      $('opt_out_url_box').style.display='none';
      $('opt_out_address_box').style.display='none';
      $('suppression_url_box').style.display='none';
    }
    $('ad_cat_review').innerHTML=json['ad_cat'];
  },
  
  handleRegisterSuccess: function(request, json, target) {
    if (this.handleTimeOut(json)) return;
    Element.hide('loading');
    if (json['errors']) {
      this.showErrors(json['errors']);
    } else if (json['notice']) {
      this.clearErrors();
      //this.showNotice(json['notice']);
      
      if ($(target)) {
        Element.update(target, request.responseText);
      }
    }
    Element.show(target);
  },
  
  completeCallback: function(response, refreshTarget) {
    json = admin.evalJSON(response);
    if (!json) { alert('There is problem in processing the request'); return; }
    admin.handleUpdateSuccess(json, refreshTarget);
  },
  
  previewCSV: function(url, filename, link_object) {
    if (! $('previewCSV_'+filename)) {
      var preview_div = document.createElement('div');
      Element.extend(preview_div);
      preview_div.setAttribute('id', 'previewCSV_'+filename);
      preview_div.setAttribute('class', 'preview_csv');
      preview_div.hide();
      link_object.parentNode.parentNode.appendChild(preview_div);
    }
    target = $('previewCSV_'+filename);
    new Ajax.Request(url, {
      method:'get',
      asynchronous:true,
      evalScripts:true,
      on404:function(request, json){admin.handle404();},
      on500:function(request, json){admin.handle500();},
      onLoading:function(request, json){admin.previewCSVLoading('previewCSV_'+filename)},
      onSuccess:function(request, json){admin.updateZone(request, json, target);},
      parameters: 'filename='+filename
    });
  },
  
  previewCSVLoading: function(preview_id) {
    if ($(preview_id)) {
      $(preview_id).update('<div class=\'loading\'>Loading...</div>');
      $(preview_id).show();
    }
  },
  
  previewTemplate: function(postfix) {
    if ($('template_zone_' + postfix) && $('preview_zone_' + postfix)) {
      $('preview_zone_' + postfix).update();
      $('template_zone_' + postfix).select('.template_zone_template').each(function(n){
        var template_content = n.innerHTML.unescapeHTML();
        if ($('id_ad_creative_ad_header_' + postfix)) {
          template_content = template_content.replace(/<ad:header>/g, $('id_ad_creative_ad_header_' + postfix).value);
        }
        if ($('id_ad_creative_ad_content_' + postfix)) {
          template_content = template_content.replace(/<ad:content>/g, $('id_ad_creative_ad_content_' + postfix).value.escapeHTML());
        }
        if ($('id_ad_creative_display_url_' + postfix)) {
          template_content = template_content.replace(/<ad:display_url>/g, $('id_ad_creative_display_url_' + postfix).value);
        }
        if ($('id_ad_creative_target_url_' + postfix)) {
          template_content = template_content.replace(/<ad:url>/g, $('id_ad_creative_target_url_' + postfix).value);
          template_content = template_content.replace(/<ad:url_url_encoded>/g, $('id_ad_creative_target_url_' + postfix).value);
        }
        
        if ($('adpicradio_' + postfix) && $('adpicradio_' + postfix).checked) {
          if (($('ad_pic_div_' + postfix)) && ($('ad_pic_div_' + postfix).select('img').first())) {
            template_content = template_content.replace(/<ad:image>/g, $('ad_pic_div_' + postfix).select('img').first().src);
          } else if ($('id_no_preview_pic_' + postfix)) {
            template_content = template_content.replace(/<ad:image>/g, $('id_no_preview_pic_' + postfix).src);
          }
        } else if ($('adpicurlradio_' + postfix) && $('adpicurlradio_' + postfix).checked) {
          template_content = template_content.replace(/<ad:image>/g, $('adpicurl_' + postfix).value);
        }
        
        if($('id_ad_swf_' + postfix)){
          var swf_contents = $('id_ad_creative_swf_text_'+postfix).value;
          template_content = swf_contents ? "<a href='"+swf_contents+"' target='_blank'>Show</a>" : '';
        }
        
        if($('id_ad_creative_html_content_' + postfix)){
          var html_contents = $('id_ad_creative_html_content_text_'+postfix).value;
          template_content = html_contents ? "<a href='"+html_contents+"' target='_blank'>Show</a>" : '';
        }
        
        template_content = template_content.replace(/<\/?tp:AdBlock>/g, '');
        template_content = template_content.replace(/<\/?tp:AdSeparator>/g, '');
        $('preview_zone_' + postfix).insert('<div class="preview_zone_template clearfix">'+template_content+'</div>');
      });
    }
  },
  
  prompt_with_required: function(options) {
    var defaults = {
      prompt_messgae: 'Value:',
      default_value: '',
      alert_message: 'Nothing Inputted.'
    }
    
    options = Object.extend(defaults, options || {});
    
    var value = prompt(options.prompt_messgae, options.default_value);
    
    if (value === '') {
      alert(options.alert_message);
      return this.prompt_with_required(options);
    }
    
    return value;
  },
  
  nl2br: function(str, is_xhtml) {
    var break_tag = (typeof is_xhtml == 'undefined' || is_xhtml) ? '<br />' : '<br>';
    
    return (str + '').replace(/\n/g, break_tag + '\n');
  },
  
  br2nl: function(str) {
    return str.replace(/(<br\s*\/?>\n?)/mig, '\n');
  },
  
  toggleAdvancedSearch: function() {
    if ($("id_filter_rows").visible()) {
      Effect.Fade("id_filter_rows");
      $("btn_expand").removeClassName("collapse");
      $("btn_expand").addClassName("expand");
    } else {
      Effect.Appear("id_filter_rows");
      $("btn_expand").removeClassName("expand");
      $("btn_expand").addClassName("collapse");
    }
  }
}

var admin = new AdsysMain();
