/*
//----------------------------------------------------------------------------
// Copyright (c) 2006-2010 Asymmetric Software. Innovation & Excellence.
// Author: Mark Samios
// http://www.asymmetrics.com
// jQuery: USDA Database Control Script
//----------------------------------------------------------------------------
// I-Metrics CMS
//----------------------------------------------------------------------------
// Script is intended to be used with the following:
//
// osCommerce, Open Source E-Commerce Solutions
// http://www.oscommerce.com
// Copyright (c) 2003 osCommerce
//
// jQuery JavaScript Library
// http://jquery.com
// Copyright (c) 2009 John Resig
//----------------------------------------------------------------------------
// Released under the GNU General Public License
//----------------------------------------------------------------------------
*/
var ctree_control = {
  imageBoxOpenFlag: false,
  imageBoxDialog: false,
  baseURL: false,
  replacementElement: false,
  boxSelector: false,
  mainSelector: false,

  // Ajax Queue Interface
  ajaxRequest: function (options){
    var request = {
      url: options.url,
      type: options.type || 'POST',
      cache: options.cache || false,
      dataType: options.dataType || 'html',
      beforeSend: function (){
        ctree_control.showAjaxMessage(options.beforeSendMsg || 'Loading, please wait...');
        ctree_control.showAjaxLoader();
      },

      //dataType: 'json',
      async: options.async || true,
      contentType: options.contentType || 'application/x-www-form-urlencoded; charset=utf-8',
      data: options.data || false,
      success: options.success,
      error: options.error,
      complete: function(robj,result){
        if( document.ajaxq.q['imageProcess'].length <= 0 ) {
          ctree_control.hideAjaxLoader();
        }
      }
    };
    //$.ajax(request);
    $.ajaxq('imageProcess', request);
    //html = result.responseText;
    //return html;
  },
  showAjaxLoader: function (){
    $('#ajaxLoader').dialog({ 
      autoOpen: true,
      resizable: false,
      modal: true
    });
    $('#ajaxLoader').dialog('open');
  },
  hideAjaxLoader: function (){
    $('#ajaxLoader').dialog('close');
  },
  showAjaxMessage: function (message){
    $('#ajaxMsg').html(message);
  },

  showDialog: function(msg, options, callbacks, styles) {
    var cbuttons = {};

    for( var func in callbacks ) {
      cbuttons[func] = callbacks[func];
    }

    cbuttons['Close'] = function() {
        var $this = $(this);
        $this.dialog('close');
    };


    if( ctree_control.imageBoxDialog && ctree_control.imageBoxOpenFlag ) {

      ctree_control.imageBoxDialog.html(msg);

      $dialog = ctree_control.imageBoxDialog.dialog();
      $dialog.data("buttons.dialog", cbuttons);

      // override dialog options on dialog data update
      for( var entry in options ) {
        $dialog.data(entry+".dialog", options[entry]);
      }

      style_string = '';
      for( var tag in styles ) {
        style_string += tag+':'+styles[tag]+';';
      }
      if( style_string.length > 0 ) {
        $dialog.attr('style', style_string);
      }
      //$dialog.data("resizable.dialog", false);
      //ctree_control.imageBoxDialog.dialog('open');
      //ctree_control.imageBoxDialog.html(msg);
      return;
    }

    ctree_control.imageBoxDialog = $('#modalBox').clone().show().appendTo(document.body).dialog({
      resizable:  options.resizable || true,
      modal:      options.modal || true,
      shadow:     options.shadow || false,
      width:      options.width || 640,
      // Do not specify height use style instead
      height:     options.height || 480,
      minWidth:   options.minWidth || 200,
      minHeight:  options.minHeight || 200,
      buttons:    cbuttons,

      close: function (){
        ctree_control.imageBoxOpenFlag = false;
        ctree_control.imageBoxDialog.dialog('destroy');
      },

      open: function() {
        var $dialog = $(this);
/*
        // Do not handle the enter on inputs
        $("input:text", $dialog).live("keypress", function(e) {
          if (e.keyCode == 13) {
            return false;
          }
        });
*/
        $dialog.html(msg);

        for( var entry in options ) {
          $dialog.data(entry+".dialog", options[entry]);
        }

        style_string = '';
        for( var tag in styles ) {
          style_string += tag+':'+styles[tag]+';';
        }
        if( style_string.length > 0 ) {
          $dialog.attr('style', style_string);
        }
        ctree_control.imageBoxOpenFlag = true;
      }

    });
    return false;
  },


  ajaxReplace: function($params, $selector) {
    var before_msg = 'Content List';

    if( $params.length > 0 ) {
      $params = '?' + $params + '&section=' + $selector;
    } else if( $selector.length > 0 ) {
      $params = '?section=' + $selector;
    }

    ctree_control.ajaxRequest({
      data: '',
      url: ctree_control.baseURL+$params,
      type: 'GET',
      beforeSendMsg: 'Searching Categories',
      complete: function(msg){
      },
      success: function(msg) {
        if( $selector  == 'box' ) {
          $(ctree_control.boxSelector).html(msg);
        } else if($selector == 'main') {
          $(ctree_control.mainSelector).html(msg);
        }
        $('select.vz_drop').unbind('change').change(function() {
          ctree_control.changeSelect(this);
          return false;
        });

      }
    });
  },


  // pre-submit callback
  showRequest: function(formData, jqForm, options) {
    // formData is an array; here we use $.param to convert it to a string to display it
    // but the form plugin does this for you automatically when it submits the data
    var queryString = $.param(formData);

    // jqForm is a jQuery object encapsulating the form element.  To access the
    // DOM element for the form do this:
    // var formElement = jqForm[0];

    //alert('About to submit: \n\n' + queryString);

    // here we could return false to prevent the form from being submitted;
    // returning anything other than false will allow the form submit to continue
    return true;
  },

  // post-submit callback
  showResponse: function(responseText, statusText)  {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server

    $replace = $(this).find('#target_abstract_zones');
    $replacement = $replace.html();
    ctree_control.replacementElement.html($replacement);

    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
    //    '\n\nThe output div should have already been updated with the responseText.');
  },


  processIndex: function(category, index) {

    category = parseInt(category);
    index = parseInt(index);
    if(category || !index) return category;

    var lists =  $(ctree_control.boxSelector).find('select');
    category = $(lists[index-1]).val();
    category = parseInt(category);

    return category;
  },

  changeSelect: function(element) {

      var path = $(element).attr('attr');
      document.location = ctree_control.baseURL+'?'+path;
      return;

      //event.preventDefault();
      var index = $(element).attr('attr');
      var category = $(element).val();
      category = ctree_control.processIndex(category, index);

      $cparam = 'category_id='+ category;
      ctree_control.ajaxReplace($cparam, 'box');
      ctree_control.ajaxReplace($cparam, 'main');
  },

  launch: function(selector, update) {

    //$('select.vz_drop').live("change", function(event) {
    $('select.vz_drop').unbind('change').change(function() {

      var i, j;
      var index = $(this).attr('attr');
      var path = '';
      var lists =  $(ctree_control.boxSelector).find('select');
      for( i=0, j=lists.length; i<j; i++ ) {
        var select = lists[i];
        var category = $(select).val();
        if( category > 0 ) {
          path += category+'_';
        }
        if( i == index ) {
          break;
        }
      }

      if( path.length ) {
        var link = ctree_control.baseURL+'?cPath='+path.substring(0, path.length-1);
        document.location = link;
      }
      return false;

      ctree_control.changeSelect(this);
      return false;

    });

    $('select.vz_drop2').unbind('change').change(function() {

      var i, j;
      var index = $(this).attr('attr');
      var path = '';
      var selector = '#cat_search_list2';
      var lists =  $(selector).find('select');
      for( i=0, j=lists.length; i<j; i++ ) {
        var select = lists[i];
        var category = $(select).val();
        if( category > 0 ) {
          path += category+'_';
        }
        if( i == index ) {
          break;
        }
      }

      if( path.length ) {
        var link = ctree_control.baseURL+'?cPath='+path.substring(0, path.length-1);
        document.location = link;
      }
      return false;

      ctree_control.changeSelect(this);
      return false;

    });


    $('#sort_products').unbind('change').change(function() {
      var i, j;
      var index = $(this).val();
      if( index == '' ) return false;

      var $parent = $(this).closest("form");
      var path = $parent.attr('action');
      path = path.replace('&amp;','&');

      var tmp_array = path.split('sort=');
      if( tmp_array.length > 1 ) {
        path = tmp_array[0];
        var tmp_array2 = tmp_array[1].split('&');
        if( tmp_array2.length > 1 ) {
          for(i=1, j=tmp_array2.length; i<j; i++) {
            if( tmp_array2[i].length ) {
              path = path + '&' + tmp_array2[i];
            }
          }
        }
      }

      if( path.length ) {
        while( path.charAt(path.length-1) == '&') {
          path = path.substring(0, path.length-1);
        }

        path += (path.indexOf('?') >= 0 ? '&' : '?');
        $(location).attr('href',path+'sort='+index);
      }
      return false;
    });


    $('#sort_mfg').unbind('change').change(function() {

      var i, j;
      var index = $(this).val();

      var $parent = $(this).closest("form");
      var path = $parent.attr('action');
      path = path.replace('&amp;','&');

      if( index != '') {
        var tmp_array = path.split('filter_id=');
        if( tmp_array.length > 1 ) {
          path = tmp_array[0];
          var tmp_array2 = tmp_array[1].split('&');
          if( tmp_array2.length > 1 ) {
            for(i=1, j=tmp_array2.length; i<j; i++) {
              if( tmp_array2[i].length ) {
                path = path + '&' + tmp_array2[i];
              }
            }
          }
        }
      }

      if( path.length ) {
        while( path.charAt(path.length-1) == '&') {
          path = path.substring(0, path.length-1);
        }
        var extra = '';
        if( index != '') {
          extra = 'filter_id='+index;
          path += (path.indexOf('?') >= 0 ? '&' : '?');
        }
        $(location).attr('href',path+extra);
      }
      return false;
    });

    $('#sort_vt').unbind('change').change(function() {
      var i, j;
      var index = $(this).val();

      var $parent = $(this).closest("form");
      var path = $parent.attr('action');
      path = path.replace('&amp;','&');

      if( index != '') {
        var tmp_array = path.split('vt_id=');
        if( tmp_array.length > 1 ) {
          path = tmp_array[0];
          var tmp_array2 = tmp_array[1].split('&');
          if( tmp_array2.length > 1 ) {
            for(i=1, j=tmp_array2.length; i<j; i++) {
              if( tmp_array2[i].length ) {
                path = path + '&' + tmp_array2[i];
              }
            }
          }
        }
      }

      if( path.length ) {
        while( path.charAt(path.length-1) == '&') {
          path = path.substring(0, path.length-1);
        }

        var extra = '';
        if( index != '') {
          extra = 'vt_id='+index;
          path += (path.indexOf('?') >= 0 ? '&' : '?');
        }
        $(location).attr('href',path+extra);
      }
      return false;
    });


  }
}


