/*******************************************************************************
STATUS TOGGLER
Toggles between TRUE and FALSE using images as indication of the value
    Red image is false
    Green image is true
Image can be change and it is not in any way dependent on the script

param status_button is an object data indexed by

@requires jQuery >= 1.3.2
@param obj
       DOM element to update
@param value
       value of the element (mostly the new value of a hidden field)
@param identifier
       element identifier (element to identify hidden fields and images used)
@param status_button
       a data compose of information of all status including the value
       image sources, status text and such. Each value currenly compose of
       these keys:
       - active_img
       - inactive_img
       - active_txt
       - inactive_txt
       - value
*/

function statusTogglerUpdateTo(new_status,obj,identifier,status_button){
    if ('' == identifier) {
        identifier = jQuery(obj).attr('id');
        var _pos = identifier.lastIndexOf('_');
        identifier = identifier.substr(0, _pos);
    }
    var hidden = jQuery('input[id="'+identifier+'"]');
    var green = jQuery('input[id="'+identifier+'_green"]');
    var red = jQuery('input[id="'+identifier+'_red"]');

    $(hidden).val('');
    $.each(status_button, function(i, val){
        // set inactive status and iterate to the next element
        if (i != new_status) {
            jQuery('img[id="'+identifier+'_'+i+'"]').attr('src', this.inactive_img);
            jQuery('img[id="'+identifier+'_'+i+'"]').attr('alt', this.inactive_txt);
            return true;
        }
        // set active status
        $(hidden).val(this.value);
        jQuery('img[id="'+identifier+'_'+i+'"]').attr('src', this.active_img);
        jQuery('img[id="'+identifier+'_'+i+'"]').attr('alt', this.active_txt);
        return true;
    });
}
/* END: STATUS TOGGLER */
/*******************************************************************************/

/*******************************************************************************
JS SECTION TOGGLER PACKAGE
/******************************************************************************/
/*
Initialize a checkbox element to be able to use the SECTION TOGGLER

@requires jQuery >= 1.3.2
@param element
       checkbox element
@param data
       DATA to be passwed on sectionToggler function
       See sectionToggler function for data requirements
*/
function initSectionToggler(element, data) {
    $(element).change(function(){
        var value = $(element).attr('checked') == true ? 1 : 0;
        data.data = $.extend(1, data.data, {'value':value, 'name':$(element).attr('name')});
        sectionToggler(element, data.page, data.action, data.data, data.callback, data.toggleOnCheck, data.toggleOnUnCheck);
    });
}
function triggerSectionToggler(element, data) {
    var value = $(element).attr('checked') == true ? 1 : 0;
    data.data = $.extend(1, data.data, {'value':value, 'name':$(element).attr('name')});
    sectionToggler(element, data.page, data.action, data.data, data.callback, data.toggleOnCheck, data.toggleOnUnCheck);
}
/*
Hide or Show a section of a page

@requires jQuery >= 1.3.2
@param element
       reference to checkbox element
@param page
       AJAX page to request
@param action
       AJAX action to request
@param data
       DATA to post
@param callback
       Function to handle the response of the AJAX request.
       NULL if default callback is to be use.
       Default callback gets 2 params [data, status]
       Customized callback gets 4 params [data, status, hide, show]
            NOTE: hide and show in customzied callback is anything that the
                  developer wants to include.
@param toggleOnCheck
       ARRAY of elements to show/hide if the request is successfully done and the checkbox is checked.
            NOTE: each value should be able to use by jQuery.
            EX: {show:['#showElementID'], hide:['#hideElementID']}
@param toggleOnUnCheck
       ARRAY of elements to show/hide if the request is successfully done and the checkbox is unchecked.
            NOTE: each value should be able to use by jQuery
            EX: {show:['#showElementID'], hide:['#hideElementID']}
*/
function sectionToggler(element, page, action, data, callback, toggleOnCheck, toggleOnUnCheck){
    AdminProductInfo.Ajax.showProcessing('');
    var url = System.url + '/ajax.php';
    data = $.extend(1, data, {'page'  :page, 'action':action});
    var postCallback = function(ajaxData, ajaxStatus){
        data._element = element;
        data._toggleOnCheck = toggleOnCheck;
        data._toggleOnUnCheck = toggleOnUnCheck;
        toggleSectionByCallback(ajaxData, ajaxStatus, data);
        AdminProductInfo.Ajax.hideProcessing();
    }
    if (typeof callback == 'function') {
        postCallback = function(data, status){
            callback(data, status, hide, show);
            AdminProductInfo.Ajax.hideProcessing();
        }
    } else if (callback != '') {
        postCallback = function(ajaxData, ajaxStatus){
            var paramData = data;
            paramData._element = element;
            paramData._toggleOnCheck = toggleOnCheck;
            paramData._toggleOnUnCheck = toggleOnUnCheck;
            // NOTE: callback function must manually close/hide the ajax processing message
            eval(callback + '(ajaxData, ajaxStatus, paramData)');
        }
    }
    if (data.page != '' && data.action != '') {
        $.post(url, data, postCallback, 'json');
    } else {
        postCallback({'error':''});
    }
}
/*
Does the dirty work of showing/hiding elements after an ajax call.

For additional information on how this function works and what data it requires, please
look at function sectionToggler (above this function) in the section postCallback, a
function callback for the ajax request.

@requires jQuery >= 1.3.2
@param ajaxData
@param ajaxStatus
@param requestData
*/
function toggleSectionByCallback(ajaxData, ajaxStatus, requestData){
    var element = requestData._element;
    var toggleOnCheck = requestData._toggleOnCheck;
    var toggleOnUnCheck = requestData._toggleOnUnCheck;
    var checked = jQuery(element).attr('checked');
    if (ajaxData.error && ajaxData.error != '') {
        if (checked == 0) {
            jQuery(element).attr('checked','checked');
            jQuery(showhide).slideDown();
        } else {
            jQuery(element).attr('checked','');
            jQuery(showhide).slideUp();
        }
        return;
    }
    if (checked == true) {
        if (jQuery.isArray(toggleOnCheck.hide)) {
            jQuery.each(toggleOnCheck.hide, function(index, value){
                jQuery(value).slideUp('fast', function(){jQuery(this).hide();});
            });
        }
        if (jQuery.isArray(toggleOnCheck.show)) {
            jQuery.each(toggleOnCheck.show, function(index, value){
                $(value).slideDown('fast', function(){jQuery(this).show();});
            });
        }
    } else {
        if (jQuery.isArray(toggleOnUnCheck.hide)) {
            jQuery.each(toggleOnUnCheck.hide, function(index, value){
                jQuery(value).slideUp('fast', function(){jQuery(this).hide();});
            });
        }
        if (jQuery.isArray(toggleOnUnCheck.show)) {
            jQuery.each(toggleOnUnCheck.show, function(index, value){
                jQuery(value).slideDown('fast', function(){jQuery(this).show();});
            });
        }
    }
}

/*
@DEPRECATED
*/
function adminCategoriesSectionTogglerCallback(data, status, args){
    var element = args[0];
    var checked = args[1];
    var showhide = args[2];
    if (data.error && data.error != '') {
        if (checked == 0) {
            $(element).attr('checked','checked');
            $(showhide).show();
        } else {
            $(element).attr('checked','');
            $(showhide).hide();
        }
        return;
    }
    if (checked == 0) {
        $(element).attr('checked','');
        $(showhide).hide();
    } else {
        $(element).attr('checked','checked');
        $(showhide).show();
    }
}
/* END: JS SECTION TOGGLER PACKAGE */
/*******************************************************************************/

/*******************************************************************************
ROW HOVER EFFECT
*/
RowOverEffect = {
    initialize: function(){
        $('.rowOverEffect')
            .addClass('moduleRow')
            .mouseover(RowOverEffect.mouseover)
            .mouseout(RowOverEffect.mouseout);
    }
    ,mouseover: function(){
        if ($(this).hasClass('moduleRow')) {
            $(this).removeClass('moduleRow').addClass('moduleRowOver');
        }
    }
    ,mouseout: function(){
        if ($(this).hasClass('moduleRowOver')) {
            $(this).removeClass('moduleRowOver').addClass('moduleRow');
        }
    }
}
function rowOverEffect(object) {
  if (jQuery(object).hasClass('moduleRow')) {
      jQuery(object).removeClass('moduleRow').addClass('moduleRowOver');
  }
}
function rowOutEffect(object) {
  if (jQuery(object).hasClass('moduleRowOver')) {
      jQuery(object).removeClass('moduleRowOver').addClass('moduleRow');
  }
}
/* END: ROW HOVER EFFECT */
/*******************************************************************************/

/*******************************************************************************
SELECT ROW EFFECT
*/
SelectRowEffect = {
    selected: null
    , params: {
        name: ''
        , onSelectCallback: function() {}
    }
}
SelectRowEffect.initialize = function() {
    jQuery.extend(true, SelectRowEffect.params, arguments[0]);
    jQuery('.selectRowEffect')
        .addClass('moduleRow')
        .click(SelectRowEffect.selected);
}
SelectRowEffect.selected = function() {
    if (jQuery(this).hasClass('moduleRowSelected')) {
        return false;
    }

    jQuery('.moduleRowSelected').removeClass('moduleRowSelected');
    jQuery(this).addClass('moduleRowSelected');

    var callback = SelectRowEffect['selectedCallbackFor' + SelectRowEffect.params.name];
    if (typeof callback == 'function') {
        callback(arguments[0]);
    }
}
SelectRowEffect.selectedCallbackForCheckoutPayment = function() {
    var that = arguments[0].currentTarget;
    jQuery(that).find('input[type="radio"][name="payment"]')
        .attr('checked', true)
        .triggerHandler('click');
}
SelectRowEffect.selectedCallbackForCheckoutShipping = function() {
    var that = arguments[0].currentTarget;
    jQuery(that).find('input[type="radio"][name="shipping"]:not(:checked)')
        .attr('checked', true)
        .triggerHandler('click');
}
/* END: SELECT ROW EFFECT */
/*******************************************************************************/

function showhide(id){
    try{
    var showbutton = '#' + id + "-show";
    var hidebutton = '#' + id + "-hide";
    var element = '#' + id;
    if ('none' == $(element).css('display')) {
        $(element).show();
        $(showbutton).hide();
        $(hidebutton).show();
        return;
    }

    $(element).hide();
    $(showbutton).show();
    $(hidebutton).hide();
    } catch(e) {}
}

/*******************************************************************************
GENERAL ITEM IMAGE FULL SIZE VIEWER

Show a dialog style UI that contains the full view of an image.  The function is
called through the use of onload event.
The parameter TYPE will be used as the reference to check for elements that is
to be binded with a CLICK event handler.

Expected html format to check:
<element img_target="image_source"></element>

Expected html format for the container:
<element class="[PARAM-TYPE]">
<element class="content"></element>
</element>

@requires jQuery >= 1.3.2
@param string type
       default: viewItemImagePopup
*/
function initializeItemImageViewer(type) {
    type = arguments[0] ? arguments[0] : 'viewItemImage';
    $('.' + type).live('click', function(event){
        var element = this;
        var source = $(this).attr('img_target');
        var close = function(){
            $(this).find('.contents').html('').hide();
            $(this).unbind('click');
        }

        var scrollTop = 0;
        if ($('body').scrollTop() > 0) {
            scrollTop = $('body').scrollTop();
        } else if ($('html').scrollTop() > 0) {
            scrollTop = $('html').scrollTop();
        }

        // callback to load the image and update the container once it is
        // completely loaded
        var callback = function() {
            $('<img src="'+source+'">').load(function(){
                $('#viewItemImagePopup .content')
                    .empty()
                    .append(this)
                    .removeClass('loading');
                var popup = jQuery('#viewItemImagePopup');
                $('#viewItemImagePopup')
                    .css({
                        'margin-top' : scrollTop - popup.innerHeight() / 2,
                        'margin-left' : $('body').scrollLeft() - popup.width() / 2
                        });

                // IE6 fix where SELECT (windowed element) is not affected by z-index and
                // it is always on top of any DIV that are positioned over it
                var iframe = jQuery('<iframe frameborder="0" marginheight="0" marginwidth="0"></iframe>').insertAfter(popup);
                iframe.offset(popup.offset());
                iframe.css({
                    'width':popup.outerWidth() + 3,
                    'height':popup.outerHeight(),
                    'opacity':0
                        });
            });
        }

        // show something while loading the image
        var popup = jQuery('#viewItemImagePopup');
        if (popup.length <= 0) {
            popup = jQuery('<div id="viewItemImagePopup" title="Click to close" style="display:none;"><p class="header"><a class="close">x</a></p><p class="content"></p></div');
            popup.appendTo('body');
        }
        popup.hide();
        popup.find('.content').html('loading...').addClass('loading');
        popup
            .click(function(){
                $(this).fadeOut('slow', close);

                // IE6 fix where SELECT (windowed element) is not affected by z-index and
                // it is always on top of any DIV that are positioned over it
                jQuery('#viewItemImagePopup').siblings('iframe').remove();
            })
            .fadeTo('slow', 1, callback)
            .css({
                'min-width':'100',
                'min-height':'100',
                'top' : '50%',
                'margin-top' : scrollTop - popup.innerHeight() / 2,
                'left' : '50%',
                'margin-left' : $('body').scrollLeft() - popup.width() / 2
                })
            ;

        event.preventDefault();
    });
}

/*
We are replacing the PopBox with jQuery inhouse developed popbox.
This function is a helper to convert all those ELEMENTs used by PopBox to something
the ItemImageViewer can understand.
This function must be called first before the "initializeItemImageViewer"
*/
function convertPbsrcToViewItemImage(type) {
    $('img[pbsrc]').each(function(k,img){
        $(img)
            .attr('onclick', '')
            .addClass('viewItemImage')
            .attr('img_target', $(img).attr('pbsrc'));
    });
}
/* END: GENERAL ITEM IMAGE FULL SIZE VIEWER */
/*******************************************************************************/

/*******************************************************************************
GENERAL SECTION TAB NAVIGATOR INITIALIZER

Will initialize the handling of Page sections that require the feature of a Tabbed
Pages.  Will handle the event when a Tab Buttons is clicked and will display
the contents of that section.

Call function only after document loads.

@note
    Temporarily specific for Product Info Page use.  Might not work properly in other pages.
@example
    <div id="tab-navigator" class="clearfix">
        <ul>
            <li><a href="#item-{tabname1}"><span>{Item Tab Name 1}</span></a></li>
            <li><a href="#item-{tabname2}"><span>{Item Tab Name 2}</span></a></li>
            ...
        </ul>
    </div>
    <div id="tab-container">
        <div class="tab-content" id="item-{tabname1}-content">{Tab Content 1 ...}</div>
        <div class="tab-content" id="item-{tabname2}-content">{Tab Content 2 ...}</div>
        ...
    </div>
@requires jQuery >= 1.3.2
@param NONE
@todo extend
*/
function tacticalInitializeTabber() {
    var clicked = 0;
    var defaultActive = $("#tab-navigator table td.active,#tab-navigator table td.default-active").length;

    // initialize tab navigator
    if (defaultActive <= 0) {
        $("#tab-navigator table td:first").addClass("active").show();
        $("#tab-container .tab-content").hide();
        $("#tab-container .tab-content:first").addClass('active').show();
    } else {
        $("#tab-container .tab-content.active").show();
    }
    $("#tab-navigator table td.item-tab").click(function() {
        if ($(this).hasClass('active')) {
            return false;
        }
    	$("#tab-navigator table td").removeClass("active").removeClass('default-active');
    	$(this).addClass("active");
    	$("#tab-container .tab-content").hide();
    	var activeTab = '#' + $(this).find("a").attr("href").split('#').pop();
    	$(activeTab + '-content').addClass('active').fadeIn();
//        if (clicked == 0) {
//            clicked += 1;
//        } else {
//            history.go(-1);
//        }
//        window.location.hash = activeTab;

        var _class = CatalogProductInfo[activeTab.replace(/[^a-z0-9]+/ig,'')];
        if (typeof _class == 'object' && typeof _class.load == 'function') {
            _class.load(this, activeTab);
        }

    	return false;
    });

    // show tab if specified in the url
    if (defaultActive <= 0) {
        var urlHash = window.location.hash.split('#');
        $('#tab-navigator table td').each(function(index, elem){
            var tab = $(elem).find('a').attr('href');
            $(urlHash).each(function(i,hash){
                if (tab != '#'+hash) {
                    return;
                }
                $("#tab-navigator table td").removeClass("active");
                $(elem).addClass("active");
                $("#tab-container .tab-content").hide();
                var activeTab = $(elem).find("a").attr("href");
                $(activeTab + '-content').addClass('active').fadeIn();
            });
        });
    }

    // focus default-active tab if set
//    var offset = jQuery('div.tab-focus').offset();
//    if (offset && offset.top) {
//        jQuery('body,html').scrollTop(offset.top - 10);
//    }
}
/* GENERAL SECTION TAB NAVIGATOR INITIALIZER */
/*******************************************************************************/

/*******************************************************************************
JS PRODUCT REVIEW FUNCTIONS
*/
function tacticalInitializeWriteReview() {

    jQuery('#review-add')
        .children('form').submit(function(){
            jQuery.post(
                'ajax.php',
                jQuery(this).serialize(),
                function(data, textStatus, request){
                    if (data.error) {
                        var offset = jQuery('#review-add .review-errors')
                            .removeClass('success')
                            .addClass('error')
                            .html(data.message)
                            .fadeIn()
                            .show()
                            .offset();
                        jQuery('body,html').scrollTop(offset.top - 10);
                    } else {
                        var offset = jQuery('#review-add-success')
                            .children('.content').html(data.message)
                            .parent().children('.close').click(function(){
                                jQuery('#review-add-success').fadeOut();
                                jQuery(this).unbind('click');
                            })
                            .parent().fadeIn().show()
                            .offset();
                        jQuery('body,html').scrollTop(offset.top - 10);
                        jQuery('#review-add .review-errors').removeClass('error').hide();
                        jQuery('#review-add').slideUp();
                        var image = new Image();
                        jQuery(image)
                            .attr('src', jQuery('#securityImageReloader').attr('href') + '&r=' + Math.floor(Math.random() * 18746))
                            .ready(function(){
                                jQuery('#securityImage').html(image).fadeIn();
                            });
                    }
                },
                'json'
            )
            return false;
        });

    jQuery('#review-dashboard .write-review a').click(function(){
        jQuery('body,html').scrollTop(jQuery(this).offset().top - 10);
        jQuery('#review-add')
            .slideDown()
            .show()
            .children('form').each(function(){
                this.reset();
            });
        var image = new Image();
        jQuery(image)
            .attr('src', jQuery('#securityImageReloader').attr('href') + '&r=' + Math.floor(Math.random() * 18746))
            .ready(function(){
                jQuery('#securityImage').html(image).fadeIn();
            });
        if (this.clicked) {
            return false;
        } else {
            this.clicked = true;
        }
        return false;
    });

    jQuery('#review-add .close').click(function(){
        jQuery('#review-add').slideUp();
        jQuery('#review-add .review-errors').removeClass('error').hide();
        return false;
    });

    jQuery('#securityImageReloader').click(function(){
        var image = new Image();
        jQuery(image)
            .attr('src', jQuery(this).attr('href') + '&r=' + Math.floor(Math.random() * 18746))
            .ready(function(){
                jQuery('#securityImage').html(image).fadeIn();
            });
        return false;
    });
}
function tacticalInitializeListReviews() {
    jQuery('#product-reviews .helpfull a').live('click', function(){
        var element = this;
        var data = jQuery(this).attr('id').split('-');
        if (data.length != 2) { return false; }
        jQuery.post(
            'ajax.php',
            {page:'product_info', action:'addReviewFeedback', review_id:data[0], feedback:data[1]},
            function(data, textStatus, request){
                if (!data.message || data.message == '') { return false; }
                jQuery(element).parents('.helpfull').addClass('helpfull-message').html(data.message);
            },
            'json'
        );
        return false;
    });
}
function tacticalGetReviews(pid, otherData, callback) {
    var thatArgs = arguments
    var data = $.extend(1, {'page':'product_info', 'action':'getReviews', 'pID':pid}, otherData.ajaxData);
    jQuery.get('ajax.php', data,
        function(data, textStatus, request){
            callback(thatArgs, data, textStatus, request);
        }, 'json');
}
function tacticalLoadReviews(pid, page) {
    jQuery('body,html').scrollTop(jQuery('.item-reviews').offset().top - 10);
    var otherData = {'ajaxData':{'pg':page}};
    var currContent = jQuery("#product-reviews-container #product-reviews").html();
    jQuery("#product-reviews-container #product-reviews").replaceWith('<div class="loading ajaxMessageLoading">Loading...</div>');
    var callback = function(thatARgs, data, textStatus, request) {
        jQuery("#product-reviews-container").replaceWith(data.data.html);
    }
    tacticalGetReviews(pid, otherData, callback);
}
/* REVIEW FUNCTIONS */

(function($){
CatalogProductInfo = {}
CatalogProductInfo.load = function(){
    $('#add-notify').click(function(){
        var sucNotify = function(data){
            $('<div>').html(data.html).dialog({
                  resizable: false
                , draggable: false
                , height:'auto'
                , width:'auto'
                , modal: true
                , title: 'Email Me When Available - Success'
                , buttons: {
                    'Continue Shopping': function(){
                        $(this).dialog('close').dialog('destroy').remove();
                    }
                },
                create: function(){
                    if (!jQuery.support.opacity) {
                        $(this).dialog('option', 'width', '460');
                    }
                }
            });
        }
        var reqNotify = function(form, onSuccess){
            var ajax_callback = function(data, textStatus, request){
                if (!Cat.Ajax.isOk(data, undefined, {title: 'Email Me When Available - Notice'})) {
                    return;
                }
                if (data.notifysaved) {
                    onSuccess(data);
                }
                sucNotify(data);
            }
            var pID = (location.href.match(/\-p\-([0-9]+)\.html/i) || []).pop()
                      || (location.href.match(/products_id=([0-9]+)/i) || []).pop();
            var data = {
                  'page' : 'product_info'
                , 'action' : 'saveNotifyMe'
                , 'product_id' : pID
            };
            $('#attributes select').each(function(){
                data['attribute_'+$(this).attr('name')] = $(this).val();
            });
            data = $.param(data)+'&'+$.param($(form).serializeArray())
            $.post(System.url + '/ajax.php', data, ajax_callback, 'json');
        }
        var doAddNotify = function(){
            var ajax_callback = function(data, textStatus, request){
                if (!Cat.Ajax.isOk(data, undefined, {title: 'Email Me When Available - Notice'})) {
                    return;
                }
                var dlgNotify = $(data.html || '<div>').dialog({
                    resizable: false,
                    draggable: false,
                    closeOnEscape: false,
                    height:'auto',
                    width:'500',
                    modal: true,
                    dialogClass: 'forAddNotifyForm',
                    title: data.title || 'Email Me When Available',
                    buttons: {
                        'Privacy Policy': function(){
                            $(dlgNotify).dialog('close');
                            var dlgPrivacy = $('<div>').html(data.policy).dialog({
                                resizable: false,
                                draggable: false,
                                height:'auto',
                                width:'500',
                                modal: true,
                                dialogClass: 'forAddNotifyPrivacy',
                                title: data.policy_title || 'Privacy Policy',
                                buttons: {
                                    'Continue': function(){
                                        $(this).dialog('close').dialog('destroy').remove();
                                        $(dlgNotify).dialog('open');
                                    },
                                    'Cancel': function(){
                                        $(this).dialog('close').dialog('destroy').remove();
                                        $(dlgNotify).dialog('close').dialog('destroy').remove();
                                    }
                                }
                            });
                        },
                        'Send': function(){
                            $(this).find('form').submit();
                        },
                        'close': function(){
                            $(this).dialog('close').dialog('destroy').remove();
                        }
                    },
                    create: function(){
                        if (!jQuery.support.opacity) {
                            $(this).dialog('option', 'width', '460');
                        }
                        $(this).find('#cpnSecurityImageReloader').click();
                    }
                });
                dlgNotify.find('form').submit(function(){
                    var onSuccess = function(){
                        $(dlgNotify).dialog('close').dialog('destroy').remove();
                    }
                    reqNotify(this, onSuccess)
                    return false;
                });
            }
            var pID = (location.href.match(/\-p\-([0-9]+)\.html/i) || []).pop()
                      || (location.href.match(/products_id=([0-9]+)/i) || []).pop();
            var data = {
                  'page' : 'product_info'
                , 'action' : 'getNotifyMeForm'
                , 'product_id' : pID
            };
            $('#attributes select').each(function(){
                data['attribute_'+$(this).attr('name')] = $(this).val();
            });
            $.get(System.url + '/ajax.php', data, ajax_callback, 'json');
        }
        doAddNotify();
    });
}
CatalogProductInfo.itemfaqs = {}
CatalogProductInfo.itemfaqs.load = function(element, activeTabName){
    var container = activeTabName + '-content';
    if ($(container).children().not('div.loading').length > 0 && $(container).html().trim() != '') { return; }
    $(container).find('div.loading').show();
    var callback = function(data, textStatus, request){
        $(container).html(data);
    }
    var data = {
          'page' : 'product_info'
        , 'action' : 'htmlGetFAQs'
        , 'product_id' : System.productId
        , 'a_name' : location.href
    };
    $.get(System.url + '/ajax.php', data, callback, 'text');
}
CatalogProductInfo.itemspecifications = {}
CatalogProductInfo.itemspecifications.load = function(element, activeTabName){
    var container = activeTabName + '-content';
    if ($(container).children().not('div.loading').length > 0 && $(container).html().trim() != '') { return; }
    $(container).find('div.loading').show();
    var callback = function(data, textStatus, request){
        $(container).html(data);
    }
    var data = {
          'page' : 'product_info'
        , 'action' : 'htmlGetSpecifications'
        , 'product_id' : System.productId
    };
    $.get(System.url + '/ajax.php', data, callback, 'text');
}
CatalogProductInfo.itemdealers = {}
CatalogProductInfo.itemdealers.load = function(element, activeTabName){
    $('#item-dealers-content .map map area').live('click', function(a){
        a.stopImmediatePropagation();
        a.preventDefault();
        if ($(this).attr('alt') == '') {
            $('#item-dealers-content .dealer-list').html('');
            return;
        }
        var callback = function(data, textStatus, request){
            if (data == '') { return; }
            $('#item-dealers-content .dealer-list').html(data);
            $('#item-dealers-content div.loading').hide();
        }
        var data = {
              'page' : 'product_info'
            , 'action' : 'getProductDealersByZone'
            , 'product_id' : System.productId
            , 'zone_name' : $(this).attr('alt')
        };
        $('#item-dealers-content div.loading').show();
        $.get(System.url + '/ajax.php', data, callback, 'text');
    });
}

User = {}
User.Auth = {}
User.Auth.isLoggedIn = function(){
    var self = this,
        caller_callback = arguments[0],
        setting = $().extend({}, {}, arguments[1]);
    var data = {
          'page' : 'user'
        , 'action' : 'isLoggedIn'
        , 'loadByAjax' : '1'
    };
    $.get(System.sUrl + '/ajax.php', data, caller_callback, 'jsonp');
}
User.Auth.logIn = function(){
    var self = this,
        caller_callback = arguments[0],
        setting = $().extend({}, {}, arguments[1]);
    var reqAuth = function(form, onSuccess){
        var ajax_callback = function(data, textStatus, request){
            if (!Cat.Ajax.isOk(data, undefined, {title: 'Sign In - Error', draggable: false})) {
                return;
            }
            if (data.loggedin) {
                onSuccess();
                caller_callback();
            }
        }
        var data = $.param({
              'page' : 'user'
            , 'action' : 'logIn'
            , 'loadByAjax' : '1'
        })+'&'+$.param($(form).serializeArray());
        $.get(System.sUrl + '/ajax.php', data, ajax_callback, 'jsonp');
    }
    User.Auth.getLogInForm(function(d,s,r){
        var dlgLogin = $('<div>').html(d.html || '').dialog({
            resizable: false,
            draggable: false,
            closeOnEscape: false,
            height:'auto',
            modal: true,
            title: d.title || 'Sign In',
            buttons: {
                'Sign In': function(){
                    $(this).find('form').submit();
                },
                'Cancel': function(){
                    $(this).dialog('close').dialog('destroy').remove();
                }
            }
        });
        dlgLogin.find('form').submit(function(){
            var onSuccess = function(){
                $(dlgLogin).dialog('close').dialog('destroy').remove();
            }
            reqAuth(this, onSuccess)
            return false;
        });
    });
}
User.Auth.getLogInForm = function(){
    var self = this,
        caller_callback = arguments[0],
        setting = $().extend({}, {}, arguments[1]);
    var data = {
          'page' : 'user'
        , 'action' : 'getLogInForm'
        , 'loadByAjax' : '1'
    };
    $.get(System.sUrl + '/ajax.php', data, caller_callback, 'jsonp');
}

Cat = {}
Cat.Dialog = {}
Cat.Dialog.ModalMessage = function(title, message, callback){
    var _myCallback = function(e, ui){
        $(this).dialog('destroy');
        if (typeof callback == 'function') {
            callback(this, e, ui);
        } else {
            $(this).remove();
        }
    }
    var _settings = arguments[3] || {};
    $('<div class="dlg-modal-msg">'+message+'</div>')
        .appendTo('body')
        .dialog($.extend(1, {resizable: false, height:'auto', modal: true, title: title, buttons: { "Ok": _myCallback }, close: _myCallback }, _settings));
}
Cat.Ajax = {}
Cat.Ajax.init = function(){
    if ($('#ajax-processing').length <= 0) {
        $('<div id="ajax-processing" style="display:none;"><div class="ap-content"></div></div>').appendTo('body')
    }
}
Cat.Ajax.showLoading = function(){
    var message = arguments[0] || 'Loading...please wait!';
    $('#ajax-processing').removeClass('error').show().find('.ap-content').html(message);
}
Cat.Ajax.hideLoading = function(){
    $('#ajax-processing').hide().find('.ap-content').html('');
}
Cat.Ajax.showProcessing = function(){
    var message = arguments[0] || 'Processing...please wait!';
    $('#ajax-processing').removeClass('error').show().find('.ap-content').html(message);
}
Cat.Ajax.hideProcessing = function(){
    $('#ajax-processing').hide().find('.ap-content').html('');
}
Cat.Ajax.showSuccess = function(){
    var message = arguments[0] || '';
    if ('' == message) {
        AdminProductInfo.Ajax.hideProcessing();
        return;
    }
    $('#ajax-processing').removeClass('error').show().find('.ap-content').html(message).end()
        .animate({'display':'hide'}, 2000, 'linear', function(){$(this).hide();});
}
Cat.Ajax.showError = function(message){
    $('#ajax-processing').addClass('error').show().find('.ap-content').html(message).end()
        .animate({'display':'hide'}, 6000, 'linear', function(){$(this).hide().removeClass('error');});
}
Cat.Ajax.isOk = function(){
    var data = arguments[0] || {}
        ,error_callback = arguments[1]
        ,dlgSettings = arguments[2] || {};
    if (typeof data == 'string') {
        Cat.Dialog.ModalMessage('Error', 'AJAX ERROR: Invalid returned data.  Please try again!', error_callback, dlgSettings);
    } else if (typeof data.error == 'string' && data.error != '') {
        Cat.Dialog.ModalMessage('Error', data.error, error_callback, dlgSettings);
    } else if (typeof data.error == 'object' && data.error.length > 0) {
        Cat.Dialog.ModalMessage('Error', data.error.join('<br />'), error_callback, dlgSettings);
    } else if (data.success != '') {
        return true;
    }
    return false;
}

})(jQuery);

/*******************************************************************************
JS TOP TABS
/******************************************************************************/
function initializeTopTabs() {
    jQuery('#prod-nav ul.lev-1').removeClass('css-hover');
    jQuery('#prod-nav ul.lev-1:not(.lev-2) li').hover(
        function(e){
            var that = this;
            jQuery(this).removeClass('show-js-hover').addClass('delay');
            __showJSHover = function(){
                if (!jQuery(that).hasClass('delay')) {
                    return;
                }
                jQuery(that).removeClass('delay').addClass('show-js-hover');
            }
            var timeoutId = setTimeout ("__showJSHover()", 200 );
            this.__timeoutId = timeoutId;
        },
        function(e){
            clearTimeout(this.__timeoutId);
            this.__timeoutId = null;
            jQuery(this).removeClass('delay show-js-hover');
        }
    );
}

/* END: JS TOP TABS */
/*******************************************************************************/

