/*
 *  jQuery selectBox (version 1.0.7)
 *
 *  Copyright 2011 Cory LaViska for A Beautiful Site, LLC.
 *
 *  http://abeautifulsite.net/blog/2011/01/jquery-selectbox-plugin/
 *
 */
if(jQuery)(function($){$.extend($.fn,{selectBox:function(method,data){var typeTimer,typeSearch='';var init=function(select,data){if(navigator.userAgent.match(/iPad|iPhone|Android/i))return false;if(select.tagName.toLowerCase()!=='select')return false;select=$(select);if(select.data('selectBox-control'))return false;var control=$('<a class="selectBox" />'),inline=select.attr('multiple')||parseInt(select.attr('size'))>1;var settings=data||{};if(settings.autoWidth===undefined)settings.autoWidth=true;control.addClass(select.attr('class')).attr('style',select.attr('style')||'').attr('title',select.attr('title')||'').attr('tabindex',parseInt(select.attr('tabindex'))).css('display','inline-block').bind('focus.selectBox',function(){if(this!==document.activeElement)$(document.activeElement).blur();if(control.hasClass('selectBox-active'))return;control.addClass('selectBox-active');select.trigger('focus')}).bind('blur.selectBox',function(){if(!control.hasClass('selectBox-active'))return;control.removeClass('selectBox-active');select.trigger('blur')});if(select.attr('disabled'))control.addClass('selectBox-disabled');if(inline){var options=getOptions(select,'inline');control.append(options).data('selectBox-options',options).addClass('selectBox-inline').addClass('selectBox-menuShowing').bind('keydown.selectBox',function(event){handleKeyDown(select,event)}).bind('keypress.selectBox',function(event){handleKeyPress(select,event)}).bind('mousedown.selectBox',function(event){if($(event.target).is('A.selectBox-inline'))event.preventDefault();if(!control.hasClass('selectBox-focus'))control.focus()}).insertAfter(select);if(!select[0].style.height){var size=select.attr('size')?parseInt(select.attr('size')):5;var tmp=control.clone().removeAttr('id').css({position:'absolute',top:'-9999em'}).show().appendTo('body');tmp.find('.selectBox-options').html('<li><a>\u00A0</a></li>');optionHeight=parseInt(tmp.find('.selectBox-options A:first').html('&nbsp;').outerHeight());tmp.remove();control.height(optionHeight*size)}disableSelection(control)}else{var label=$('<span class="selectBox-label" />'),arrow=$('<span class="selectBox-arrow" />');label.text($(select).find('OPTION:selected').text()||'\u00A0');var options=getOptions(select,'dropdown');options.appendTo('BODY');control.data('selectBox-options',options).addClass('selectBox-dropdown').append(label).append(arrow).bind('mousedown.selectBox',function(event){if(control.hasClass('selectBox-menuShowing')){hideMenus()}else{event.stopPropagation();options.data('selectBox-down-at-x',event.screenX).data('selectBox-down-at-y',event.screenY);showMenu(select)}}).bind('keydown.selectBox',function(event){handleKeyDown(select,event)}).bind('keypress.selectBox',function(event){handleKeyPress(select,event)}).insertAfter(select);disableSelection(control)}select.addClass('selectBox').data('selectBox-control',control).data('selectBox-settings',settings).hide()};var getOptions=function(select,type){var options;switch(type){case'inline':options=$('<ul class="selectBox-options" />');if(select.find('OPTGROUP').length){select.find('OPTGROUP').each(function(){var optgroup=$('<li class="selectBox-optgroup" />');optgroup.text($(this).attr('label'));options.append(optgroup);$(this).find('OPTION').each(function(){var li=$('<li />'),a=$('<a />');li.addClass($(this).attr('class'));a.attr('rel',$(this).val()).text($(this).text());li.append(a);if($(this).attr('disabled'))li.addClass('selectBox-disabled');if($(this).attr('selected'))li.addClass('selectBox-selected');options.append(li)})})}else{select.find('OPTION').each(function(){var li=$('<li />'),a=$('<a />');li.addClass($(this).attr('class'));a.attr('rel',$(this).val()).text($(this).text());li.append(a);if($(this).attr('disabled'))li.addClass('selectBox-disabled');if($(this).attr('selected'))li.addClass('selectBox-selected');options.append(li)})}options.find('A').bind('mouseover.selectBox',function(event){addHover(select,$(this).parent())}).bind('mouseout.selectBox',function(event){removeHover(select,$(this).parent())}).bind('mousedown.selectBox',function(event){event.preventDefault();if(!select.selectBox('control').hasClass('selectBox-active'))select.selectBox('control').focus()}).bind('mouseup.selectBox',function(event){hideMenus();selectOption(select,$(this).parent(),event)});disableSelection(options);return options;case'dropdown':options=$('<ul class="selectBox-dropdown-menu selectBox-options" />');if(select.find('OPTGROUP').length){select.find('OPTGROUP').each(function(){var optgroup=$('<li class="selectBox-optgroup" />');optgroup.text($(this).attr('label'));options.append(optgroup);$(this).find('OPTION').each(function(){var li=$('<li />'),a=$('<a />');li.addClass($(this).attr('class'));a.attr('rel',$(this).val()).text($(this).text());li.append(a);if($(this).attr('disabled'))li.addClass('selectBox-disabled');if($(this).attr('selected'))li.addClass('selectBox-selected');options.append(li)})})}else{if(select.find('OPTION').length>0){select.find('OPTION').each(function(){var li=$('<li />'),a=$('<a />');li.addClass($(this).attr('class'));a.attr('rel',$(this).val()).text($(this).text());li.append(a);if($(this).attr('disabled'))li.addClass('selectBox-disabled');if($(this).attr('selected'))li.addClass('selectBox-selected');options.append(li)})}else{options.append('<li>\u00A0</li>')}}options.data('selectBox-select',select).css('display','none').appendTo('BODY').find('A').bind('mousedown.selectBox',function(event){event.preventDefault();if(event.screenX===options.data('selectBox-down-at-x')&&event.screenY===options.data('selectBox-down-at-y')){options.removeData('selectBox-down-at-x').removeData('selectBox-down-at-y');hideMenus()}}).bind('mouseup.selectBox',function(event){if(event.screenX===options.data('selectBox-down-at-x')&&event.screenY===options.data('selectBox-down-at-y')){return}else{options.removeData('selectBox-down-at-x').removeData('selectBox-down-at-y')}selectOption(select,$(this).parent());hideMenus()}).bind('mouseover.selectBox',function(event){addHover(select,$(this).parent())}).bind('mouseout.selectBox',function(event){removeHover(select,$(this).parent())});disableSelection(options);return options}};var destroy=function(select){select=$(select);var control=select.data('selectBox-control');if(!control)return;var options=control.data('selectBox-options');options.remove();control.remove();select.removeClass('selectBox').removeData('selectBox-control').removeData('selectBox-settings').show()};var showMenu=function(select){select=$(select);var control=select.data('selectBox-control'),settings=select.data('selectBox-settings'),options=control.data('selectBox-options');if(control.hasClass('selectBox-disabled'))return false;hideMenus();if(settings.autoWidth)options.css('width',control.outerWidth()-(parseInt(control.css('borderLeftWidth'))+parseInt(control.css('borderLeftWidth'))));options.css({top:control.offset().top+control.outerHeight()-(parseInt(control.css('borderBottomWidth'))),left:control.offset().left});switch(settings.menuTransition){case'fade':options.fadeIn(settings.menuSpeed);break;case'slide':options.slideDown(settings.menuSpeed);break;default:options.show(settings.menuSpeed);break}var li=options.find('.selectBox-selected:first');keepOptionInView(select,li,true);addHover(select,li);control.addClass('selectBox-menuShowing');$(document).bind('mousedown.selectBox',function(event){if($(event.target).parents().andSelf().hasClass('selectBox-options'))return;hideMenus()})};var hideMenus=function(){if($(".selectBox-dropdown-menu").length===0)return;$(document).unbind('mousedown.selectBox');$(".selectBox-dropdown-menu").each(function(){var options=$(this),select=options.data('selectBox-select'),control=select.data('selectBox-control'),settings=select.data('selectBox-settings');switch(settings.menuTransition){case'fade':options.fadeOut(settings.menuSpeed);break;case'slide':options.slideUp(settings.menuSpeed);break;default:options.hide(settings.menuSpeed);break}control.removeClass('selectBox-menuShowing')})};var selectOption=function(select,li,event){select=$(select);li=$(li);var control=select.data('selectBox-control'),settings=select.data('selectBox-settings');if(control.hasClass('selectBox-disabled'))return false;if(li.length===0||li.hasClass('selectBox-disabled'))return false;if(select.attr('multiple')){if(event.shiftKey&&control.data('selectBox-last-selected')){li.toggleClass('selectBox-selected');var affectedOptions;if(li.index()>control.data('selectBox-last-selected').index()){affectedOptions=li.siblings().slice(control.data('selectBox-last-selected').index(),li.index())}else{affectedOptions=li.siblings().slice(li.index(),control.data('selectBox-last-selected').index())}affectedOptions=affectedOptions.not('.selectBox-optgroup, .selectBox-disabled');if(li.hasClass('selectBox-selected')){affectedOptions.addClass('selectBox-selected')}else{affectedOptions.removeClass('selectBox-selected')}}else if(event.metaKey){li.toggleClass('selectBox-selected')}else{li.siblings().removeClass('selectBox-selected');li.addClass('selectBox-selected')}}else{li.siblings().removeClass('selectBox-selected');li.addClass('selectBox-selected')}if(control.hasClass('selectBox-dropdown')){control.find('.selectBox-label').text(li.text())}var i=0,selection=[];if(select.attr('multiple')){control.find('.selectBox-selected A').each(function(){selection[i++]=$(this).attr('rel')})}else{selection=li.find('A').attr('rel')}control.data('selectBox-last-selected',li);if(select.val()!==selection){select.val(selection);select.trigger('change')}return true};var addHover=function(select,li){select=$(select);li=$(li);var control=select.data('selectBox-control'),options=control.data('selectBox-options');options.find('.selectBox-hover').removeClass('selectBox-hover');li.addClass('selectBox-hover')};var removeHover=function(select,li){select=$(select);li=$(li);var control=select.data('selectBox-control'),options=control.data('selectBox-options');options.find('.selectBox-hover').removeClass('selectBox-hover')};var keepOptionInView=function(select,li,center){if(!li||li.length===0)return;select=$(select);var control=select.data('selectBox-control'),options=control.data('selectBox-options'),scrollBox=control.hasClass('selectBox-dropdown')?options:options.parent(),top=parseInt(li.offset().top-scrollBox.position().top),bottom=parseInt(top+li.outerHeight());if(center){scrollBox.scrollTop(li.offset().top-scrollBox.offset().top+scrollBox.scrollTop()-(scrollBox.height()/2))}else{if(top<0){scrollBox.scrollTop(li.offset().top-scrollBox.offset().top+scrollBox.scrollTop())}if(bottom>scrollBox.height()){scrollBox.scrollTop((li.offset().top+li.outerHeight())-scrollBox.offset().top+scrollBox.scrollTop()-scrollBox.height())}}};var handleKeyDown=function(select,event){select=$(select);var control=select.data('selectBox-control'),options=control.data('selectBox-options'),totalOptions=0,i=0;if(control.hasClass('selectBox-disabled'))return;switch(event.keyCode){case 8:event.preventDefault();typeSearch='';break;case 9:case 27:hideMenus();removeHover(select);break;case 13:if(control.hasClass('selectBox-menuShowing')){selectOption(select,options.find('LI.selectBox-hover:first'),event);if(control.hasClass('selectBox-dropdown'))hideMenus()}else{showMenu(select)}break;case 38:case 37:event.preventDefault();if(control.hasClass('selectBox-menuShowing')){var prev=options.find('.selectBox-hover').prev('LI');totalOptions=options.find('LI:not(.selectBox-optgroup)').length;i=0;while(prev.length===0||prev.hasClass('selectBox-disabled')||prev.hasClass('selectBox-optgroup')){prev=prev.prev('LI');if(prev.length===0)prev=options.find('LI:last');if(++i>=totalOptions)break}addHover(select,prev);keepOptionInView(select,prev)}else{showMenu(select)}break;case 40:case 39:event.preventDefault();if(control.hasClass('selectBox-menuShowing')){var next=options.find('.selectBox-hover').next('LI');totalOptions=options.find('LI:not(.selectBox-optgroup)').length;i=0;while(next.length===0||next.hasClass('selectBox-disabled')||next.hasClass('selectBox-optgroup')){next=next.next('LI');if(next.length===0)next=options.find('LI:first');if(++i>=totalOptions)break}addHover(select,next);keepOptionInView(select,next)}else{showMenu(select)}break}};var handleKeyPress=function(select,event){select=$(select);var control=select.data('selectBox-control'),options=control.data('selectBox-options');if(control.hasClass('selectBox-disabled'))return;switch(event.keyCode){case 9:case 27:case 13:case 38:case 37:case 40:case 39:break;default:if(!control.hasClass('selectBox-menuShowing'))showMenu(select);event.preventDefault();clearTimeout(typeTimer);typeSearch+=String.fromCharCode(event.charCode||event.keyCode);options.find('A').each(function(){if($(this).text().substr(0,typeSearch.length).toLowerCase()===typeSearch.toLowerCase()){addHover(select,$(this).parent());keepOptionInView(select,$(this).parent());return false}});typeTimer=setTimeout(function(){typeSearch=''},1000);break}};var enable=function(select){select=$(select);select.attr('disabled',false);var control=select.data('selectBox-control');if(!control)return;control.removeClass('selectBox-disabled')};var disable=function(select){select=$(select);select.attr('disabled',true);var control=select.data('selectBox-control');if(!control)return;control.addClass('selectBox-disabled')};var setValue=function(select,value){select=$(select);select.val(value);value=select.val();var control=select.data('selectBox-control');if(!control)return;var settings=select.data('selectBox-settings'),options=control.data('selectBox-options');control.find('.selectBox-label').text($(select).find('OPTION:selected').text()||'\u00A0');options.find('.selectBox-selected').removeClass('selectBox-selected');options.find('A').each(function(){if(typeof(value)==='object'){for(var i=0;i<value.length;i++){if($(this).attr('rel')==value[i]){$(this).parent().addClass('selectBox-selected')}}}else{if($(this).attr('rel')==value){$(this).parent().addClass('selectBox-selected')}}});if(settings.change)settings.change.call(select)};var setOptions=function(select,options){select=$(select);var control=select.data('selectBox-control'),settings=select.data('selectBox-settings');switch(typeof(data)){case'string':select.html(data);break;case'object':select.html('');for(var i in data){if(data[i]===null)continue;if(typeof(data[i])==='object'){var optgroup=$('<optgroup label="'+i+'" />');for(var j in data[i]){optgroup.append('<option value="'+j+'">'+data[i][j]+'</option>')}select.append(optgroup)}else{var option=$('<option value="'+i+'">'+data[i]+'</option>');select.append(option)}}break}if(!control)return;control.data('selectBox-options').remove();var type=control.hasClass('selectBox-dropdown')?'dropdown':'inline',options=getOptions(select,type);control.data('selectBox-options',options);switch(type){case'inline':control.append(options);break;case'dropdown':control.find('.selectBox-label').text($(select).find('OPTION:selected').text()||'\u00A0');$("BODY").append(options);break}};var disableSelection=function(selector){$(selector).css('MozUserSelect','none').bind('selectstart',function(event){event.preventDefault()})};switch(method){case'control':return $(this).data('selectBox-control');break;case'settings':if(!data)return $(this).data('selectBox-settings');$(this).each(function(){$(this).data('selectBox-settings',$.extend(true,$(this).data('selectBox-settings'),data))});break;case'options':$(this).each(function(){setOptions(this,data)});break;case'value':if(!data)return $(this).val();$(this).each(function(){setValue(this,data)});break;case'enable':$(this).each(function(){enable(this)});break;case'disable':$(this).each(function(){disable(this)});break;case'destroy':$(this).each(function(){destroy(this)});break;default:$(this).each(function(){init(this,method)});break}return $(this)}})})(jQuery);
//=== Tractr Box ==============================================
//@param link: ID of link to open the tractrBox
//@param object: ID of the tractrBox to open
function tractrBox(link, object) {
    $(link).bind("click", function(event) {
		event.preventDefault();
		$('.tractrOverlay').fadeTo(200, 0.7, function() {
		    $(object).fadeIn(200);
        });
		return false;
	});
	$(object).children('.close').bind("click", function(event) {
		event.preventDefault();
        $(object).fadeOut(200, function() {
		    $('.tractrOverlay').fadeOut(200);
		});
		$('#shopping-cart .comment textarea').hide();
		return false;
    });
}
var nCartItem = 0 || Number($('#shopping-cartCounter .counter').text());

//=== updateOrder ==============================================================
//@description : Updates the order (Express Order and Shopping Cart)
function updateOrder() {
    $('.total, .big-total').remove();
    //Add temporary class for deleting
    $('#shopping-cart').find('.list-order').find('tbody').children('tr.item').addClass('deleting');
    //Get order list via Ajax
    $.getJSON('/order/list?v=' +new Date().getTime(), function(data) {

        if(data.length > 0)
        {
            $('#shopping-cart').find('.order').show();
            $('#shopping-cart').find('.order-empty').hide();
            $('.sidebar-products').find('.order').show();
            $('.sidebar-products').find('.order-empty').hide();
            $(data).each(function() {
                if(this.fields)
                {
                    //Check if available
                    if(this.fields.in_stock)
                        var available = word_available;
                    else
                        var available = word_notAvailable;
                    //Check if item is already in the list
                    if($('#cart-order-product-' +this.fields.content_id).length > 0 )
                    {
                        //Update the quantity in Express Order table
                        $('#order-product-' +this.fields.content_id).find('.qty').find('input').val(this.fields.quantity);
                        //Update and price the quantity in Shopping Cart table
                        $('#cart-order-product-' +this.fields.content_id).find('.qty').html(this.fields.quantity);
                        $('#cart-order-product-' +this.fields.content_id).find('.available').html(available);
                        $('#cart-order-product-' +this.fields.content_id).find('.item-totalPrice').html(Number(this.fields.price * this.fields.quantity).toFixed(2));
                        $('#cart-order-product-' +this.fields.content_id).find('.item-price').html(Number(this.fields.price).toFixed(2));
                        $('#cart-order-product-' +this.fields.content_id).find('.tps').html(Number(this.fields.tps * this.fields.quantity).toFixed(2));
                        $('#cart-order-product-' +this.fields.content_id).find('.tvq').html(Number(this.fields.tvq * this.fields.quantity).toFixed(2));
                        //Remove 'deleting' class from the current item
                        $('#cart-order-product-' +this.fields.content_id).removeClass('deleting');
                    }
                    //Item is not in the list
                    else
                    {
                        //Add checked
                        $('#product-' +this.fields.content_id).addClass('checked');
                        //Generate Express Order table line for the item
                        $('.sidebar-products').find('.list-order').children('tbody').append(' \
                            <tr class="item" id="order-product-' +this.fields.content_id+ '"> \
                                <td style="padding-right: 10px">' +this.fields.title_en+ '</td> \
                                <td class="qty"><input type="text" maxlength="4" value="' +this.fields.quantity+ '"/></td> \
                                <td class="delete"><img src="' +MEDIA_URL+ 'img/ui/btn_delete.png"/></td> \
                            </tr> \
                        ');
                        //Generate Shopping Cart table line for the item
                        $('#shopping-cart').find('.list-order').find('tbody').append(' \
                            <tr class="item" id="cart-order-product-' +this.fields.content_id+ '"> \
                                <td>' +this.fields.title_en+ '</td> \
                                <td class="qty">' +this.fields.quantity+ '</td> \
                                <td class="available">' +available+ '</td> \
                                <td>$ <span class="item-totalPrice">' +Number(this.fields.price * this.fields.quantity).toFixed(2)+ '</span> ($ <span class="item-price">' +Number(this.fields.price).toFixed(2)+ '</span> ' +word_each+ ')</td> \
                                <td><span class="tps">$ '+Number(this.fields.tps * this.fields.quantity).toFixed(2)+'</span></td> \
                                <td><span class="tvq">$ '+Number(this.fields.tvq * this.fields.quantity).toFixed(2)+'</span></td> \
                                <td class="delete"><img src="' +MEDIA_URL+ 'img/ui/btn_delete.png"/></td> \
                            </tr> \
                        ');
                       nCartItem++;
                       updateCartItemCounter();
                    }
                }
            });
        }
        //Order empty
        else
        {
            $('#shopping-cart').find('.order').hide();
            $('#shopping-cart').find('.order-empty').show();
            $('.sidebar-products').find('.order').hide();
            $('.sidebar-products').find('.order-empty').show();
        }
        
    }).always(function() {
        //Remove items that were not found in the returned order list
        $('#shopping-cart').find('.list-order').find('tbody').children('.deleting').each(function() {
            var productId = $(this).attr('id').substr($(this).attr('id').lastIndexOf('product-'));
            //Remove product line + checked
            $('#' +productId).removeClass('checked');
            $('#order-' +productId).remove();
            $('#cart-order-' +productId).remove();
                       nCartItem--;
                       updateCartItemCounter();
        });
        //Re-alternate the shopping cart table
        $('#shopping-cart').find('.list-order').find('tbody').find('tr').each(function(i) {
            if(i % 2 == 0)
                $(this).removeClass('alt');
            else
                $(this).addClass('alt');
        });

        $('#shopping-cart').find('.list-order').find('tbody').append(' \
            <tr class="total"> \
            <td></td> \
            <td colspan=2 class="right-text right">TOTAL:</td> \
            <td class="right-text">$ <span class="order-total"></span></td> \
            <td class="right-text">$ <span class="order-total-tps"></span></td> \
            <td class="right-text">$ <span class="order-total-tvq"></span></td> \
            <td></td> \
            </tr> \
            <tr class="big-total"> \
            <td></td> \
            <td colspan=2 class="right-text right">'+ BIG_TOTAL +':</td> \
            <td class="right-text">$ <span class="order-big-total"></span></td> \
            <td></td> \
            <td></td> \
            <td></td> \
            </tr> \
            ');

        //Get Order infos
        $.getJSON('/order/info', function(data) {
          $('#shopping-cart').find('.order-total').html(Number(data.total).toFixed(2));
          $('#shopping-cart').find('.order-big-total').html(Number(data.big_total).toFixed(2));
          $('#shopping-cart').find('.order-total-tps').html(Number(data.total_tps).toFixed(2));
          $('#shopping-cart').find('.order-total-tvq').html(Number(data.total_tvq).toFixed(2));
        });
        assignDeleteProduct();
        assignAddProduct();
    });
	
}
function updateCartItemCounter(){
	// debug("updateCartItemCounter = ");
	// 	debug("nCartItem = "+nCartItem);
    if(nCartItem<=0){ $('#shopping-cartCounter').hide(); }
	else{ 
		$('#shopping-cartCounter').show();
		$('#shopping-cartCounter .counter').text(nCartItem);
	}
}
//=== AssignAddProduct ==============================================================
//@description : Assigns "Add item to Order" onclick function to Add buttons
function assignAddProduct() {
    //Plus button to add product
    $('.list-products.auth').children('li').children('.plus').unbind('click').click(function() {
        debug('add product');
		var productId = $(this).parent().attr('id').substr($(this).parent().attr('id').lastIndexOf('product-') + 8);
        //Ajax call to remove the product
        $.get('/order/add/product/' +productId+ '/qty1', function(data) {
            //Update the order list
            updateOrder();
        });
    });
    //Changing the quantity from inputs of the sidebar
    $('.sidebar-products').find('.qty').find('input').unbind('keyup').keyup(function() {
        var productId = $(this).parent().parent().attr('id').substr($(this).parent().parent().attr('id').lastIndexOf('product-') + 8);
        //Ajax call to remove the product
        $.get('/order/add/product/' +productId+ '/changeQty' +$(this).val(), function(data) {
            //Update the order list
            $('.sidebar-products').find('.qty').find('input').unbind('blur').blur(function() {
                updateOrder();
            });
        });
    });
}
//=== AssignDeleteProduct ==============================================================
//@description : Assigns "Delete item from Order" onclick function to Delete buttons
function assignDeleteProduct() {
    $('.list-order').find('tr').find('.delete').find('img').unbind('click').click(function() {
        var productId = $(this).parent().parent().attr('id').substr($(this).parent().parent().attr('id').lastIndexOf('product-') + 8);
        //Ajax call to remove the product
        $.get('/order/remove/product/' +productId, function(data) {
            //Update the order list
            updateOrder();
        });
    });
}
//=== closeGridBox ==============================================================
//@description : Close a grid box -- Animated grid
function closeGridBox(grid) {
    //Hide hidden content
    $(grid.closingBlock.object).find('.hidden-content').fadeOut(grid.animateFadeTime, function() {
        //Expand to the left if Last block of the line
        if($(grid.closingBlock.object).hasClass('c' +grid.nbCols))
        {
            $(grid.closingBlock.object).animate({
                width: grid.block.baseWidth,
                marginLeft: '+=' +grid.block.moveLengthX
            }, grid.block.animateExpandTime, function() {
                 openGridBox(grid);
            });
        }
        else
        {
            $(grid.closingBlock.object).animate({
                    width: grid.block.baseWidth
                }, grid.block.animateExpandTime, function() {
                 openGridBox(grid);
            });
        }
        //Normal Behavior for closing block
        if(grid.closingBlock.col < grid.nbCols)
        {
            $(grid.object).children('div').each(function(i) {
                if(i > grid.closingBlock.index)
                {
                    //Last block of the line behavior
                    if($(this).hasClass('c' +grid.nbCols))
                    {
                        $(this).animate({
                            left: '+=' +(grid.nbCols - 1)*grid.block.moveLengthX,
                            top: '-=' +grid.block.moveLengthY
                        }, grid.block.animateMoveTime);
                    }
                    //Normal behavior
                    else
                    {
                        $(this).animate({
                            left: '-=' +grid.block.moveLengthX
                        }, grid.block.animateMoveTime);
                    }
                }
            });
        }
        //Last block of the line behavior for closing block
        else
        {
            //Move the previous block to the bottom
            var previousBlock = $('.r' +grid.closingBlock.row+ '.c' +(grid.closingBlock.col - 1));
            var indexToStart = parseInt($(previousBlock).index()) + parseInt(grid.nbCols) - 1;
            $(previousBlock).animate({
                top: '-=' +grid.block.moveLengthY
            }, grid.block.animateMoveTime);
            //Move every block after the one we're expanding
            $(grid.object).children('div').each(function(i) {
                if(i > indexToStart)
                {
                    //Last block behavior
                    if($(this).hasClass('c' +grid.nbCols))
                    {
                        $(this).animate({
                            left: '+=' +(grid.nbCols - 1)*grid.block.moveLengthX,
                            top: '-=' +grid.block.moveLengthY
                        }, grid.block.animateMoveTime);
                    }
                    //Normal behavior
                    else
                    {
                        $(this).animate({
                            left: '-=' +grid.block.moveLengthX
                        }, grid.block.animateMoveTime);
                    }
                }
            });
        }
    });
    $(grid.closingBlock.object).find('.div-content').children('h5').css('color', '#666');
    $(grid.closingBlock.object).removeClass('open');
}
//=== openGridBox ==============================================================
//@description : Open a grid box -- Animated grid
function openGridBox(grid)
{
    if(grid.indexClose != grid.activeBlock.index)
    {
        //Normal behavior
        if(grid.activeBlock.col < grid.nbCols)
        {
            //Move every block after the one we're expanding
            $(grid.object).children('div').each(function(i) {
                if(i > grid.activeBlock.index)
                {
                    if($(this).hasClass('c' +grid.nbCols))
                    {
                        $(this).animate({
                            left: '-=' +(grid.nbCols - 1)*grid.block.moveLengthX,
                            top: '+=' +grid.block.moveLengthY
                        }, grid.block.animateMoveTime);
                    }
                    else
                    {
                        $(this).animate({
                            left: '+=' +grid.block.moveLengthX
                        }, grid.block.animateMoveTime);
                    }
                }
            });
        }
        //Last block of the line behavior
        else
        {
            var previousBlock = $('.r' +grid.activeBlock.row+ '.c' +(grid.activeBlock.col - 1));
            var indexToStart = parseInt($(previousBlock).index()) + parseInt(grid.nbCols) - 1;
            //Move the previous block to the bottom
            $(previousBlock).animate({
                top: '+=' +grid.block.moveLengthY
            }, grid.block.animateMoveTime);
            //Move every block from the new position of the previous block
            $(grid.object).children('div').each(function(i) {
                if(i > indexToStart)
                {
                    if($(this).hasClass('c' +grid.nbCols))
                    {
                        $(this).animate({
                            left: '-=' +(grid.nbCols - 1)*grid.block.moveLengthX,
                            top: '+=' +grid.block.moveLengthY
                        }, grid.block.animateMoveTime);
                    }
                    else
                    {
                        $(this).animate({
                            left: '+=' +grid.block.moveLengthX
                        }, grid.block.animateMoveTime);
                    }
                }
            });
        }
        //Expand to the left if Last block of the line
        if($(grid.activeBlock.object).hasClass('c' +grid.nbCols))
        {
            $(grid.activeBlock.object).animate({
                width: grid.block.expandWidth,
                marginLeft: -grid.block.moveLengthX
            }, grid.animateExpandTime, function() {
                //Show hidden content (with a little hack to avoid title moving around)
                $(grid.activeBlock.object).find('.hidden-content').fadeTo(grid.animateFadeTime, 1);
            }).find('.hidden-content').fadeTo(0, 0.01);
        }
        else
        {
            $(grid.activeBlock.object).animate({
                width: grid.block.expandWidth
            }, grid.animateExpandTime, function() {
                //Show hidden content (with a little hack to avoid title moving around)
                $(grid.activeBlock.object).find('.hidden-content').fadeTo(grid.animateFadeTime, 1);
            }).find('.hidden-content').fadeTo(0, 0.01);
        }
        $(grid.activeBlock.object).find('.div-content').children('h5').css('color', '#ccc');
        $(grid.activeBlock.object).addClass('open');
    }
}
word_each = '';
word_available = '';
word_notAvailable = '';
//=====================================================================================================
//=== On page load actions ============================================================================
$(document).ready(function() {
    //-- Words --------------------------------------------------
    updateCartItemCounter();
	
	var word_each_tmp = $('#word_each').html();
    word_each = word_each_tmp;
    $('#word_each').remove();
    var word_available_tmp = $('#word_available').html();
    word_available = word_available_tmp;
    $('#word_available').remove();
    var word_notAvailable_tmp = $('#word_notAvailable').html();
    word_notAvailable = word_notAvailable_tmp;
    $('#word_notAvailable').remove();
	debug('add acction slideDown textearea');
	$('#shopping-cart .comment .right-link').click(function(event){
		event.preventDefault();
		debug('slideDown textearea');
		$('#shopping-cart .comment textarea').slideToggle('slow');
	});
    //--- Submit Filter form on change of a select field
    $('#filter-form').children('select').change(function() {
        $('#filter-form').submit();
    });
    //--- Express order sidebar follows on scroll (animated fixed)
    if($('.sidebar-products').length)
    {
        var $sidebar   = $(".sidebar-products"),
        $window    = $(window);
        offset     = $sidebar.offset();
        $window.scroll(function() {
            if ($window.scrollTop() > offset.top && $sidebar.height() < $window.height() - 300) {
                $sidebar.stop().animate({
                    marginTop: $window.scrollTop() - offset.top + 230
                }, 250);
            } else {
                $sidebar.stop().animate({
                    marginTop: 0
                }, 250);
            }
        });
    }
    updateOrder();
    assignAddProduct();
    //--- Order viewProduct - Add to shopping cart ---------------------------------------------------------
    $('.viewProduct').find('.list-product').submit(function() {
        $(this).find('tbody').find('tr').each(function() {
            var productId = $(this).attr('id').substr($(this).attr('id').lastIndexOf('product-') + 8);
            qty = parseInt($(this).find('input').val());
            //Check if it's a number at least of 1
            if(typeof(qty) != 'number' || qty < 1)
                return
            //Ajax call to remove the product
            $.get('/order/add/product/' +productId+ '/qty' +qty, function(data) {
                //Update the order list
                updateOrder();
            });
        })
        $(this).fadeOut(400, function() {
            $('#msg_addedItem').fadeIn(400);
        });
        return false;
    });
    //--- Shopping Cart tractrBox
    tractrBox('#shopping-cartBoxLink', '#shopping-cart');
    tractrBox('#express-order-submit', '#shopping-cart');

    //--- Order Sent tractrBox
    tractrBox('#order-sentLink', '#order-sent');

    //--- Share tractrBox
    tractrBox('#shareBoxLink', '#shareBox');
    //--- Login tractrBox
    tractrBox('.loginBoxLink', '#loginBox');
    //--- Change Password tractrBox
    tractrBox('#change-passwordBoxLink', '#change-passwordBox');
    //--- Registered tractrBox
    tractrBox('#registeredBoxLink', '#registeredBox');
    
    //--- Order Details tractrBox
	$('.order-details').each(function() {
        tractrBox('#' +$(this).attr('id')+ 'Link', '#' +$(this).attr('id'));
    });
	var l = location.href;
	var redir_arg = /next=/gi;
	if( l.match(redir_arg) )
		$('#loginBoxLink').trigger('click');
    //Order sent
    if(location.href.lastIndexOf('catalog/list/orderSent') > 1)
        $('#order-sentLink').trigger('click');
    //Registered
    if(location.href.lastIndexOf('registered') > 1)
        $('#registeredBoxLink').trigger('click');
    //Login error
    if(location.href.lastIndexOf('login/error') > 1)
        $('.loginBoxLink').trigger('click');
    //--- Form Inputs placeholder text ------------------------------
    $('input[type=text].placeholder, textarea.placeholder').each(function() {
        var placeholder = $(this).val();
        $(this).focus(function() {
            if($(this).val() == placeholder)
            {
                $(this).val('');
                $(this).css('font-size', '12px');
                $(this).css('text-transform', 'none');
            }
        });
        $(this).blur(function() {
            if($(this).val() == '')
            {
                $(this).val(placeholder);
                $(this).css('font-size', '10px');
                $(this).css('text-transform', 'uppercase');
            }
        });
    });
    //--- Form Inputs password placeholder text ------------------------------
    $('input[type=password].placeholder').each(function() {
        var id = $(this).attr('id');
        //Make sure there is a fake field for placeholder
        if($('#fake_' +id).length)
        {
            $(this).hide();
            $('#fake_' +id).show();
            //Show real password field on focus
            $('#fake_' +id).focus(function() {
                $('#fake_' +id).hide();
                $('#' +id).show().focus();
            });
            //Back to fake field if still empty
            $('#' +id).blur(function() {
                if($('#' +id).val() == '')
                {
                    $('#' +id).hide();
                    $('#fake_' +id).show();
                }
            });
        }
    });
    //--- Slider home--------------------------------------
    //Hide all
    $('.sliderHome img').css('left', '960px');
    $('.sliderHome img:first').css('left', '0px');
    $('.sliderHome_nav li:first').addClass('selected');
    var currentIndex = $('.sliderHome img:first').index();
    var sliderTimeout;
    //Define de sliderTime callback
    sliderTimer = function() {
        sliderTimeout = setTimeout(function() {
            $('.sliderHome img').eq(currentIndex).stop().animate({
                left: '-960px'
            }, 500, function() {
                $(this).css('left', '960px');
            });
            $('.sliderHome_nav li').removeClass('selected');
            //Show first img if current is the last
            if(!$('.sliderHome img').eq(currentIndex + 1).length)
            {
                $('.sliderHome img').eq(0).stop().animate({
                    left: '0px'
                }, 500);
                $('.sliderHome_nav li').eq(0).addClass('selected');
            }
            //Show next img
            else
            {
                $('.sliderHome img').eq(currentIndex + 1).stop().animate({
                    left: '0px'
                }, 500);
                $('.sliderHome_nav li').eq(currentIndex + 1).addClass('selected');
            }
            //Define next index
            if(!$('.sliderHome img').eq(currentIndex + 1).length)
                currentIndex = 0;
            else
                currentIndex += 1;
            //Callback
            sliderTimer();
        }, 5000);
    }
    sliderTimer();
    //Set slider home navigation
    $('.sliderHome_nav li').click(function() {
        var navIndex = $(this).index();
        clearTimeout(sliderTimeout);
        $('.sliderHome img').eq(currentIndex).stop().animate({
            left: '-960px'
        }, 500, function() {
            $(this).css('left', '960px');
        });
        $('.sliderHome_nav li').removeClass('selected');
        $('.sliderHome img').eq(navIndex).stop().animate({
            left: '0px'
        }, 500);
        $('.sliderHome_nav li').eq(navIndex).addClass('selected');
        //Define next index
        currentIndex = navIndex;
        //Callback
        sliderTimer();
    });
    //--- Slider product img
    $('.sliderImg img.big').hide();
    $('.details .infos').hide();
    $('#img-' + PRODUCT_ID_CONTEXT).show();
    $('#infos-' + PRODUCT_ID_CONTEXT).show();
    $('.sliderImg .thumb img').hover(function() {
        var id = $(this).attr('id').substr(10);
        $('.sliderImg img.big').hide();
        $('#img-' +id).show();
        $('.details .infos').hide();
        $('#infos-' +id).show();
    },
    function() {
        $('.sliderImg img.big').hide();
        $('.details .infos').hide();
		// console.log(PRODUCT_ID_CONTEXT);
        $('#img-' + PRODUCT_ID_CONTEXT).show();
        $('#infos-' + PRODUCT_ID_CONTEXT).show();
    });
    //--- Wholesalers list
    $('.wholesaler-info').not(':first').hide();
    $('#select_wholesaler').change(function() {
        $('.wholesaler-info').hide();
        $('#wholesaler-' +$(this).val()).show();
    });
    //--- Tabs
    $('.link-tab').click(function() {
        //Show the tab
        $('.tab').hide();
        $('#' +$(this).attr('id').substr(5)).show();
        //Change 'current' tab link
        $('.link-tab').removeClass('current');
        $(this).addClass('current');
    });
    //--- Select boxes
    $('select').each(function() {
        var selectBox = $(this).selectBox({ menuTransition: 'slide', menuSpeed: 'fast' });
        if($(this).attr('id') == 'product_status')
            $(this).selectBox('control').addClass('last');
    });
    //--- Checkboxes
    $('input:checkbox').each(function() {
        var chkId = $(this).attr('id');
        //Hide the real checkbox
        $(this).hide();
        //Create false checkbox
        $(this).after('<div class="fakeCheckbox" id="chk-' +chkId+ '"></div>');
        //Give 'checked' class if the real checkbox is checked
        if($(this).is(':checked'))
            $('#chk-' +chkId).addClass('checked');
        //Create click event to simulate checking the real checkbox
        $('#chk-' +chkId).click(function() {
            if($(this).hasClass('checked'))
            {
                $(this).removeClass('checked');
                $('#' +chkId).attr('checked', false);
            }
            else
            {
                $(this).addClass('checked');
                $('#' +chkId).attr('checked', true);
            }
        });
    });
    //--- Account form 'Same as shipping adress' checkbox
    $('#chk-id_billing_same_as_shipping').click(function() {
        if($('#id_billing_same_as_shipping').is(':checked'))
        {
            //Copy shipping adress to billing
            $('[id^="id_shipping"]').each(function() {
                var inputId = $(this).attr('id').substr(12);
                $('#id_billing_' +inputId).val($(this).val());
            });
        }
    });
        //Uncheck "billing same as shipping" if values are changed
        $('[id^="id_billing"]').keyup(function() {
            $('#id_billing_same_as_shipping').attr('checked', false);
            $('#chk-id_billing_same_as_shipping').removeClass('checked');
        });
        //Copy shipping values when they change
        $('[id^="id_shipping"]').keyup(function() {
            if($('#id_billing_same_as_shipping').is(':checked'))
            {
                var inputId = $(this).attr('id').substr(12);
                $('#id_billing_' +inputId).val($(this).val());
            }
        });
	//Make elements affected with the noselect class not selectable
	$('.noselect').live('selectstart dragstart', function(e){ e.preventDefault(); return false; });
    //-----------------------------------------------------------------------------------------------------------------------------------
    //--- Animated grid ------------------------------------------------------------------------------------------------------------------
    $('.animatedGrid').children('div').each(function(i) {
        var col = $(this).attr('class').substr(4, 1);
        var row = $(this).attr('class').substr(1, 1);
        //Partners grid
        if($('.animatedGrid').hasClass('partners'))
        {
            $(this).css('position', 'absolute');
            $(this).css('left', col*188 - 188);
            $(this).css('top', row*234 - 234 + 20);
            // $('.animatedGrid').css('height', row*234);
			$('.animatedGrid').css('height', 468);
        }
        //Services grid
        else
        {
            $(this).css('position', 'absolute');
            $(this).css('left', col*224- 224);
            $(this).css('top', row*270 - 270 + 50);
            $('.animatedGrid').css('height', row*270 + 200);
        }
        nbCols = 0;
        $('.animatedGrid').children('div').each(function(i) {
            if(nbCols < $(this).attr('class').substr(4, 1))
                nbCols = $(this).attr('class').substr(4, 1);
        });
        $('.c' +nbCols).addClass('last');
    });
    $('.animatedGrid').children('div').click(function() {
        //Make sure nothing is animated
        if(!$('.animatedGrid').find('div').is(':animated'))
        {
            grid = new Object;
            grid.object = $('.animatedGrid');
            grid.block = new Object;
            grid.activeBlock = new Object;
            grid.block.baseWidth = 154;
            grid.block.baseHeight = 200;
            //Partners grid
            if($(grid.object).hasClass('partners'))
                grid.block.margin = 17;
            //Services grid
            else
                grid.block.margin = 35;
            grid.block.expandWidth = (grid.block.baseWidth + grid.block.margin)*2;
            grid.block.moveLengthX = grid.block.baseWidth + grid.block.margin*2;
            grid.block.moveLengthY = grid.block.baseHeight + grid.block.margin*2;
            grid.block.animateMoveTime = 200;
            grid.block.animateExpandTime = 200;
            grid.block.animateFadeTime = 200;
            grid.nbCols = 0;
            grid.nbRows = 0;
            grid.activeBlock.object = this;
            grid.activeBlock.col = $(grid.activeBlock.object).attr('class').substr(4, 1);
            grid.activeBlock.row = $(grid.activeBlock.object).attr('class').substr(1, 1);
            grid.activeBlock.index = $(grid.activeBlock.object).index();
            grid.indexClose;
            //Count number of rows and cols
            $(grid.object).children('div').each(function(i) {
                if(grid.nbRows < $(this).attr('class').substr(1, 1))
                    grid.nbRows = $(this).attr('class').substr(1, 1);
                if(grid.nbCols < $(this).attr('class').substr(4, 1))
                    grid.nbCols = $(this).attr('class').substr(4, 1);
            });
            //Close if there is one opened
            var boxOpened;
            $(grid.object).children('div').each(function(i) {
                if($(this).hasClass('open'))
                {
                    grid.closingBlock = new Object;
                    grid.closingBlock.object = this;
                    grid.closingBlock.col = $(grid.closingBlock.object).attr('class').substr(4, 1);
                    grid.closingBlock.row = $(grid.closingBlock.object).attr('class').substr(1, 1);
                    grid.closingBlock.index = $(grid.closingBlock.object).index();
                    boxOpened = true;
                    closeGridBox(grid);
                    grid.indexClose = i;
                }
            });
            if(!boxOpened)
                 openGridBox(grid);
        }
    });
    //---------------------------------------------------------------------------------------------------------------------------------------
});
	var debugMode = 'true';
	var traceInfo = 'true';
	// DEBUG LOG
	if(typeof debug != 'function') {
		function debug(msg){
			if(window.console && console.debug && debugMode ){  console.debug(msg); }else if(window.console && console.log && debugMode ){ console.log(msg); }
		}
	}
	function warning(msg){
		if(window.console && console.warn ){ console.warn(msg); }
		else if(window.console && console.error ){ console.error(msg); }
		else if(window.console && console.info ){ console.info(msg); }
		else if(window.console && console.log ){ console.log(msg); }
		alert(msg);
	}
	function info(msg){
		if(window.console && console.info && traceInfo ){ console.info(msg); }
	}
	function log_dump(arr,level){
		if(!level) level = 0;
		if(debugMode){ try{ console.groupCollapsed("arr:"+(typeof arr)+" = "+arr+" : "+arr.length); }catch(e){} }
		debug( dump(arr,level) );
		if(debugMode){ try{ console.groupEnd(); }catch(e){} }
	}
	/**
	 * Function : dump()
	 * Arguments: The data - array,hash(associative array),object
	 *    The level - OPTIONAL
	 * Returns  : The textual representation of the array.
	 * This function was inspired by the print_r function of PHP.
	 * This will accept some data as the argument and return a
	 * text that will be a more readable version of the
	 * array/hash/object that is given.
	 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
	 */
	function dump(arr,level) {
		var dumped_text = "";
		if(!level) level = 0;
		//The padding given at the beginning of the line.
		var level_padding = "";
		for(var j=0;j<level+1;j++) level_padding += "    ";
		if(typeof(arr) == 'object') { //Array/Hashes/Objects
			for(var item in arr) {
				var value = arr[item];
				if(typeof(value) == 'object') { //If it is an array,
					dumped_text += level_padding + "'" + item + "' ...\n";
					dumped_text += dump(value,level+1);
				} else {
					dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
				}
			}
		} else { //Stings/Chars/Numbers etc.
			dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
		}
		return dumped_text;
	}
	function isArray(obj) {
	    return obj.constructor == Array;
	}
// =====================
// = BROWSER DETECTION =
// =====================
	function IE(){
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
			var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			if (ieversion>=9){		return {'version':9, 'msg':"You're using IE9 or above"}; }
			else if (ieversion>=8){	return {'version':8, 'msg':"You're using IE8 or above"}; }
			else if (ieversion>=7){	return {'version':7, 'msg':"You're using IE7 or above"}; }
			else if (ieversion>=6){	return {'version':6, 'msg':"You're using IE6 or above"}; }
			else if (ieversion>=5){	return {'version':5, 'msg':"You're using IE5 or above"}; }
		}else{
			return false;
		}
	}
	function FF(){
		if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		 var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			if (ffversion>=3){		return {'version':3, 'msg':"You're using FF 3.x or above"}; }
			else if (ffversion>=2){	return {'version':2, 'msg':"You're using FF 2.x"}; }
			else if (ffversion>=1){	return {'version':1, 'msg':"You're using FF 1.x"}; }
		}else{
			return false;
		}
	}
	function opera(){
		if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
		 var oprversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			if (oprversion>=10){		return {'version':3, 'msg':"You're using Opera 10.x or above"}; }
			else if (oprversion>=9){	return {'version':2, 'msg':"You're using Opera 9.x"}; }
			else if (oprversion>=8){	return {'version':1, 'msg':"You're using Opera 8.x"}; }
			else if (oprversion>=7){	return {'version':1, 'msg':"You're using Opera 7.x"}; }
		}else{
			return false;
		}
	}
	// IE6 MESSAGE
	function IE6_alert(){
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		  //test for MSIE x.x;
		  var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		  if (ieversion<=6) {
			if( hasClass(document.getElementByTagName("body"), "fr") ){
				//do something
				document.write("<DIV id=ie6msg><H4>Savez-vous que votre navigateur est obsolète&nbsp;?</H4><P>Pour naviguer de la manière la plus satisfaisante sur notre site, nous recommandons que vous procédiez à une mise à jour de votre navigateur. La version actuelle est <A class=getie7 href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx'>Internet Explorer&nbsp;8</A>. La mise à jour est gratuite. Si vous utilisez un PC au travail, veuillez contacter votre service informatique.</P><P>Si vous le souhaitez, vous pouvez aussi essayer d'autres navigateurs Web populaires comme par exemple <A class=ie6expl href='http://mozilla.com'>FireFox</A>, <A class=ie6expl href='http://www.opera.com'>Opera</A> ou <A class=ie6expl href='http://www.apple.com/safari/download/'>Safari</A></P></DIV>");
			}else{
				document.write("<DIV id=ie6msg><H4> Do you know your browser is outdated </ H4> <P> To navigate the most satisfactory manner on our site, we recommend that you perform an update of your browser. The current version is <A class=getie7 href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx'> Internet Explorer 8 </ A>. The update is free. If you use a PC at work, please contact your IT department. </ P> If you wish, you can also try other popular web browsers such as <A class = ie6expl href = 'http:/ / mozilla.com '> FireFox </ A> <A class=ie6expl href='http://www.opera.com'> Opera </ A> or <a class = ie6expl href = ' http://www .apple.com / safari / download / '>Safari</A></P></DIV>");
			}
		}
		}
	}
// CLASSES MANIPULATION : OLD METHODES
	function hasClass(ele,cls) {
		return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
	}
	function addClass(ele,cls) {
		if (!this.hasClass(ele,cls)) ele.className += " "+cls;
	}
	function removeClass(ele,cls) {
		if (hasClass(ele,cls)) {
			var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
			ele.className=ele.className.replace(reg,' ');
		}
	}
// GEOMETRIC
// FIND POSITION
// Developped for ypgconquest
function findPos( oElement ) {
	if( typeof( oElement.offsetParent ) != 'undefined' ) {
		for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
			posX += oElement.offsetLeft;
			posY += oElement.offsetTop;
		}
		debug("posX: "+posX+", posY: "+posY);
		return [ posX, posY ];
	} else {
		debug("oElement.x: "+oElement.x+", oElement.y: "+oElement.y);
		return [ oElement.x, oElement.y ];
  }
}
// ==============
// = wappalyzer =
// ==============
// INSERT wappalyzer script to the current page header and pop the results
function wappalyzer(){
var body = document.getElementsByTagName('body')[0];
		if ( body )
		{
			var script = document.getElementById('wappalyzer-script');
			if ( script )
			{
				body.removeChild(script);
			}
			script = document.createElement('script');
			script.type = 'text/javascript';
			script.src  = 'http://wappalyzer.com/bookmarklet/analyze.js.php?' + Math.ceil(9999999 * Math.random());
			script.id   = 'wappalyzer-script';
			body.appendChild(script);
		}
		void(0);
}
// ==========
// = STRING =
// ==========
function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
// ==========
// = PHP.JS =
// ==========
function function_exists (function_name) {
    if (typeof function_name == 'string'){
        return (typeof this.window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}
function isset () {
	var a = arguments, l = a.length, i = 0, undef;
	if (l === 0) { throw new Error('Empty isset'); };
	while (i !== l) { if (a[i] === undef || a[i] === null) { return false;  }; i++; }; return true;
}
function empty (mixed_var) {
    var key;
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
    return false;
}
// ===========================================================
// = COOKIES  -  http://www.quirksmode.org/js/cookies.html   =
// ===========================================================
function createCookie(name,value,days,domain) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/ ; domain="+domain;
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

