Ext.ns('Ext.ux');

Ext.ux.Menu = Ext.extend(Ext.util.Observable, {
    direction: 'horizontal',
    delay: 0.2,
    autoWidth: true,
    transitionType: 'fade',
    transitionDuration: 0.3,
    animate: true,
    currentClass: 'current',

    constructor: function(elId, config) {
        config = config || {};
        Ext.apply(this, config);

        Ext.ux.Menu.superclass.constructor.call(this, config);

        this.addEvents(
            'show',
            'hide',
            'click'
        );

        this.el = Ext.get(elId);

        this.initMarkup();
        this.initEvents();

        this.setCurrent();
    },

    initMarkup: function(){
        this.container = this.el.wrap({cls: 'ux-menu-container', style: 'z-index: ' + --Ext.ux.Menu.zSeed});
        this.items = this.el.select('li');

        this.el.addClass('ux-menu ux-menu-' + this.direction);
        this.el.select('>li').addClass('ux-menu-item-main');

        this.el.select('li:has(>ul)').addClass('ux-menu-item-parent').each(function(item) {
            item.down('a')
                .addClass('ux-menu-link-parent');
                //.createChild({tag: 'span', cls: 'ux-menu-arrow'});
        });
        
        this.el.select('li:first-child>a').addClass('ux-menu-link-first');
        this.el.select('li:last-child>a').addClass('ux-menu-link-last');

        // create clear fixes for the floating stuff
        this.container.addClass('ux-menu-clearfix');

        // if autoWidth make every submenu as wide as its biggest child;
        if(this.autoWidth) {
            this.doAutoWidth();
        }

        var subs = this.el.select('ul');
        subs.addClass('ux-menu-sub');
        
        //ie6 and ie7/ie8 quirksmode need iframes behind the submenus
        if(Ext.isBorderBox || Ext.isIE7) {
            subs.each(function(item) {
                item.parent().createChild({tag: 'iframe', cls: 'ux-menu-ie-iframe'})
                    .setWidth(item.getWidth())
                    .setHeight(item.getHeight());
            });
        }
        
        subs.addClass('ux-menu-hidden');
    },

    initEvents: function() {
        this.showTask = new Ext.util.DelayedTask(this.showMenu, this);
        this.hideTask = new Ext.util.DelayedTask(function() {
            this.showTask.cancel();
            this.hideAll();
            this.fireEvent('hide');
        }, this);

        this.el.hover(function() {
            this.hideTask.cancel();
        }, function() {
            this.hideTask.delay(this.delay*1000);
        }, this);

        // for each item that has a submenu, create a mouseenter function that shows its submenu
        // delay 5 to make sure enter is fired after mouseover
        this.el.select('li.ux-menu-item-parent').on('mouseenter', this.onParentEnter, false, {me: this, delay: 5});

        // listen for mouseover events on items to hide other items submenus and remove hovers
        this.el.on('mouseover', function(ev, t) {
            this.manageSiblings(t);
            // if this item does not have a submenu, the showMenu task for a sibling could potentially still be fired, so cancel it
            if(!Ext.fly(t).hasClass('ux-menu-item-parent')) {
                this.showTask.cancel();
            }
        }, this, {delegate: 'li'});

        this.el.on('click', function(ev, t) {
            return this.fireEvent('click', ev, t, this);
        }, this, {delegate: 'a'})
    },

    onParentEnter: function(ev, link, o) {
        var item = Ext.get(this),
            me = o.me;

        // if this item is in a submenu and contains a submenu, check if the submenu is not still animating
        if(!item.hasClass('ux-menu-item-main') && item.parent('ul').hasActiveFx()) {
            item.parent('ul').stopFx(true);
        }

        // if submenu is already shown dont do anything
        if(!item.child('ul').hasClass('ux-menu-hidden')) {
            return;
        }
        
        me.showTask.delay(me.delay*1000, false, false, [item]);   
    },

    showMenu : function(item) {
		
        var menu = item.child('ul'),
            x = y = 0;
			
	
        item.select('>a').addClass('ux-menu-link-hover');

        // some different configurations require different positioning
        if(this.direction == 'horizontal' && item.hasClass('ux-menu-item-main')) {
            y = item.getHeight()+1;
        }
        else {
            x = item.getWidth()+1;
        }

        // if its ie, force a repaint of the submenu
        if(Ext.isIE) {
            menu.select('ul').addClass('ux-menu-hidden');
            // ie bugs...
            if(Ext.isBorderBox || Ext.isIE7) {
                item.down('iframe').setStyle({left: (x - 3) + 'px', top: (y - 1) + 'px', display: 'block'});
            }
        }
		if(item.child('ol'))
		{
			menu.setStyle({left: (x - 3) + 'px', top: (-149) + 'px'}).removeClass('ux-menu-hidden');
		}else{
			menu.setStyle({left: (x - 3) + 'px', top: (y - 1) + 'px'}).removeClass('ux-menu-hidden');
		}
        

        if(this.animate) {
            switch(this.transitionType) {
                case 'slide':
                    if(this.direction == 'horizontal' && item.hasClass('ux-menu-item-main')) {
                        menu.slideIn('t', {
                            duration: this.transitionDuration
                        });
                    }
                    else {
                        menu.slideIn('l', {
                            duration: this.transitionDuration
                        });
                    }
                break;

                default:
                    menu.setOpacity(0.001).fadeIn({
                        duration: this.transitionDuration
                    });
                break
            }
        }
        
        this.fireEvent('show', item, menu, this);
    },

    manageSiblings: function(item) {
        var item = Ext.get(item);
        item.parent().select('li.ux-menu-item-parent').each(function(child) {
            if(child.dom.id !== item.dom.id) {
                child.select('>a').removeClass('ux-menu-link-hover');
                child.select('ul').stopFx(false).addClass('ux-menu-hidden');
                if (Ext.isBorderBox || Ext.isIE7) {
                    child.select('iframe').setStyle('display', 'none');
                }
            }
        });
    },

    hideAll: function() {
        this.manageSiblings(this.el);
    },
    
    setCurrent: function() {
        var els = this.el.query('.' + this.currentClass);
        if(!els.length) {
            return;
        }
        var item = Ext.get(els[els.length-1]).removeClass(this.currentClass).findParent('li', null, true);
        while(item && item.parent('.ux-menu')) {
            item.down('a').addClass(this.currentClass);
            item = item.parent('li');
        }
    },

    doAutoWidth: function() {
        var fixWidth = function(sub) {
            var widest = 0;
            var items = sub.select('>li');

            sub.setStyle({width: 3000 + 'px'});
            items.each(function(item) {
                widest = Math.max(widest, item.getWidth());
            });

            widest = Ext.isIE ? widest + 1 : widest;
            items.setWidth(widest + 'px');
            sub.setWidth(widest + 'px');
        }

        if(this.direction == 'vertical') {
            this.container.select('ul').each(fixWidth);
        }
        else {
            this.el.select('ul').each(fixWidth);
        }
        
    }
});

Ext.ux.Menu.zSeed = 10000;



var lastid = '';
function subDiv(it){
	if( lastid != '' &&  it != lastid)
	{	
		var l = $(it);
		if(l.style.display == 'block')
		{
			l.style.display = 'none;'
		}
	}
	var o = $(it);
	var d = o.style.display
	if(d == 'none'){
		o.style.display = 'block';	
	}
	else if(d == 'block'){
		o.style.display = 'none';
	}	
}

function contentSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
	var x = document.getElementById('content');
	x.style.height = (myHeight - 70) + 'px';
}

function changeIMG(id, src){
	trg = id.split("-");
	t = 'image-'+trg[1];
	$( '#' + t ).attr({
		src: src
	});
}

function changeITEMIMG(id, src, href, img_id){
	trg = id.split("-");
	t = 'image-'+trg[1];
	l = 'link-'+trg[1];
	$( '#' + t ).attr({	src: src });
	$('#' + l).attr({ href: href });
	$('#store-color').val(img_id);
}

function changeITEMIMG2( img_id, img_src ){
	$('#store-color').val(img_id);
	$('#image-src-container').val(img_src);
}

function changeValue(trg, dir){
	var tmp = $( '#' + trg ).val();
	if(dir == 'inc'){
		tmp++;
	}
	else if(dir == 'dec'){
		if(tmp != 0){
			tmp--;
		}
	}
	$( '#' + trg ).val( tmp );
}

function refreshBasketInfo(lang){
	$.getJSON(
		"./index.php?node=shop_basket&cmd=getbasketdetails",
		function(json){
			var lang_id = lang;
			if( lang_id == 12)
			{
				//kr is the money
				if( json.sum_price_no != null){
					// if ( json.sum_price_no >= 1500 ) $('#shop_basket_info_price').html(json.sum_price_no);
					// else $('#shop_basket_info_price').html( parseInt( json.sum_price_no ) + 69 );
					$('#shop_basket_info_price').html(json.sum_price_no);
				}else{
					$('#shop_basket_info_price').html(0);
				}
			}else if( lang_id == 3)
			{
				//euro
				if( json.sum_price_us != null){
					$('#shop_basket_info_price').html(json.sum_price_us);
				}else{
					$('#shop_basket_info_price').html(0);
				}
			}			
			if( json.sum_quantity != null )
			{
				$('#shop_basket_info_items').html(json.sum_quantity);
			}else{
				$('#shop_basket_info_items').html('no ');
			}
		}
	);
}
/**
 * functions for shop basket view
 */
function updateBasket(){
	var p = { 
		color:			$('#ajax_store-color').val() 
		,size:			$('#select-item-size').html() 
		,row_id:		$('#ajax_row_id').val()
		,product_id:	$('#ajax_product_id').val()
	};
	var j = $.toJSON(p);
	$.getJSON(
		"./index.php?node=shop_basket&cmd=updateitem", 
		{params: j},
		function(json){
			document.location.href='./index.php?node=shop_basket_view' ;
		}
	); 
	return false;
}
function addToBasket(lang){
	var p = { 
		color:			$('#store-color').val() 
		,size:			$('#select-item-size').html() 
		,quantity:		$('#qty-input').val()
		,product_id:	$('#product_id').val()
	};
	var j = $.toJSON(p);
	$('#cover_table').css("display","table");
	$.getJSON(
		"./index.php?node=shop_basket&cmd=additem", 
		{params: j},
		function(json){
		/*	if(json.session_id){
				$('#link-to-view-basket').attr({href:'./index.php?node=shop_basket_view&session_id='+json.session_id});
			}*/
			refreshBasketInfo(lang);
			$('#information_window').html(json.msg);
			
			$('#cover_table_content').css("display","table");
			setTimeout(function(){
				$('#information_window').html('');
				$('#cover_table').css("display","none");
				$('#cover_table_content').css("display","none");
			},3000);
		}
	); 
	return false;
}

function newAddToBasket(lang){
	var qty_input = $('#qty-input').val();
	if( qty_input.indexOf('-') != -1 ){
		quantity = qty_input.substring(1,qty_input.length);
	}else{
		quantity = qty_input;
	}
	var p = { 
		color:			$('#store-color').val() 
		,size:			$('#select-item-size').html() 
		,quantity:		quantity
		,product_id:	$('#product_id').val()
	};
	var j = $.toJSON(p);
	$.getJSON(
		"http://store.follestad.com/index.php?node=shop_basket&cmd=additem", 
		{params: j},
		function(json){
			var img_src = $('#image-src-container').val();
			$('#confirm-item-add-content').html('<a href="./index.php?node=shop_basket_view"><img title="confirm image" alt="conf image" src="' + img_src + '" /><p style="margin-top:5px;">' + json.msg + '</p></a>');
			Ext.fly('confirm-item-add').setStyle('display', 'inline');
			Ext.fly('confirm-item-add').stopFx().animate({
			    height: {to : 155}
			}, 0.25);
			//$('#confirm-item-add').html(json.msg);
			
			setTimeout(function(){
				$('#confirm-item-add-content').html('');
				Ext.fly('confirm-item-add').stopFx().animate({
				    height: {to : 0}
				}, 0.40);
			},3500);
			setTimeout(function(){
				Ext.fly('confirm-item-add').setStyle('display', 'none');
			},3900);
			refreshBasketInfo(lang);
		}
	); 
	return false;
}

function changeQTY(trg, dir){
	var tmp = $( '#' + trg ).val();
	if(dir == 'inc'){
		tmp++;
	}
	else if(dir == 'dec'){
		if(tmp != 0){
			tmp--;
		}
	}
	$( '#' + trg ).val( tmp );
	var newtrg = trg.split("-");
	var itemID = newtrg[2].split("_");
	var prize = $('#price-' + newtrg[2]).html();
	var subtotal = parseFloat( prize * tmp );
	var oldSub = $('#sub-total-' + newtrg[2]).html();
	var change = parseFloat(subtotal - oldSub);
	$('#sub-total-' + newtrg[2]).html(subtotal);
	corrTOTAL(change);
	
	if (tmp == 0) {
		//remove row and item from bag 
		var newtrg = trg.split("-");
		var itemID = newtrg[2].split("_");
		removeItemFromBag(itemID[0], newtrg[2], newtrg[3]);
		updateQTY(newtrg[3], tmp);
	}else{
		updateQTY(newtrg[3], tmp);
	}
	
}
function updateQTY(row_id, qty){
	var p = { 
		quantity:qty
		,row_id: row_id
	};
	var j = $.toJSON(p);
	$.getJSON(
		"./index.php?node=shop_basket&cmd=updateqty", 
		{params: j},
		function(json){
			refreshBasketInfo();
		}
	); 
}
function corrTOTALS(obj){
	var t = obj.id;
	var nT = t.split("-");
	
	var c = $("#"+t).val();
	var prize = $('#price-' + nT[2]).html();
	var subtotal = parseFloat( prize * obj.value );
	$('#sub-total-' + nT[2]).html(subtotal);
	corrTOTAL(subtotal);
	
	if( obj.value == 0){
		var test = nT[2];
		var itemID  = test.split("_");
		removeItemFromBag( itemID[0], nT[2], nT[3] );
		updateQTY(nT[3], obj.value);
	}else{
		updateQTY(nT[3], obj.value);
	}

}

function remITEM(obj, r){
	var p = { 
		product_id:	id
		,row_id: r
	};
	var j = $.toJSON(p);
	$.getJSON(
		"./index.php?node=shop_basket&cmd=removeitem", 
		{params: j},
		function(json){
			var target = $('#' + obj);
			target.remove();
	
			check2RELOADBasket();
			refreshBasketInfo();
		}
	); 
	
	
	return false;
}

function removeItemFromBag(id, tg, bID){
	
	var p = { 
		product_id:	id
		,row_id: bID
	};
	var j = $.toJSON(p);
	$.getJSON(
		"./index.php?node=shop_basket&cmd=removeitem", 
		{params: j},
		function(json){
			refreshBasketInfo();
		}
	);
	
	var target = $('#item-row-' + tg);
	target.remove();
	
	check2RELOADBasket();
	return false;
	
}
function corrTOTAL( nSub ){
	
	var sum = $('#total-price').html();
	var currSHIP = $('#shipping-price').html();
	if(!isNaN(sum)){
		var nSum = parseFloat( parseInt( sum ) + parseInt( nSub ) );
		var newSum = 0;
		if ( nSum >= 1500 ){
			$('#shipping-price').html('0');
			if(currSHIP == 69){
				newSum = parseFloat( parseInt( nSum ) - parseInt( 69 ) ); 
			}else{
				newSum = nSum;
			}
			
		} 
		else{
			$('#shipping-price').html('69');
			newSum =  parseFloat( parseInt( 69 ) + parseInt( nSum ) );
		}  
		
		$('#total-price').html(newSum);
	}else{
		$('#total-price').html(nSub);
		if ( nSub >= 1500 ) $('#shipping-price').html('0');
		else  $('#shipping-price').html('69');
	}
}

function initialNUMBERS(){
	var prizes = $(".post-price");
	
	for(i=0; i < prizes.length; i++){
		t = prizes[i].id;
		tt = t.split('-');
		
		var price = $('#price-' + tt[1]).html();
		var qty = $('#qty-input-' + tt[1]).val();
		var nSub = parseFloat( price * qty );
		
		$('#sub-total-' + tt[1]).html( nSub );
		corrTOTAL(nSub);
	}
}

/**
 * show and load the selected items container div 
 */
function modifyAttr( id, row_id ){
	$.ajax({
	   type: "POST",
	   url: "index.php",
	   data: "node=ashop&id=" + id + "&row_id=" + row_id,
	   success: function(msg){
			$('#current_product').html(msg);
			$('#cover_table').css("display","table");
			$('#cover_table_content').css("display","table");
			CB_Init();
	   }
	 });
}


function check2RELOADBasket(){
	var xx =  Ext.fly("shopping-bag-table").child('tr');
	if(xx)
	{
	   // alert(xx.id); 
	   return true;
	}
	else
	{
		window.location = './index.php?node=shop_basket_view' ;
	}
}

/**
 * hide and clear the actual items container.
 */
function hideUpdate( trg ){
	$('#current_product').html('');
	$('#cover_table').css("display","none");
	$('#cover_table_content').css("display","none");
	return false;
}
function checkbasket( logged_in, site_url, o ){
	
//	alert(logged_in + "  site_url: " + site_url );
	
	if(logged_in == 1)
	{
		o.href="http://" + site_url + "/post_order.php";
		myLytebox.start(o, false, true); 
	}
}
function changeMainPicture(id, trg){
//	$("#main-pict-switcher > *").css("display", "none");
//	$("#store-" + id).css("display", "block");
	$('#image-src-container').val(trg);
	var newing = id.split('_');
	$("#mainswitch-" + id).addClass('active');
	if(newing[1] == 1){
		$("#mainswitch-" + newing[0] + '_0').removeClass('active');
	}
	if(newing[1] == 0){
		$("#mainswitch-" + newing[0] + '_1').removeClass('active');
	}
}
function showLinksContainer( id ){
	$("#mainswitch-" + id + "_0").addClass('active');
	$("#mainswitch-" + id + "_1").removeClass('active');
	$("#main-pict-switcher > *").css("display", "none");
	$("#store-" + id).css("display", "block");
}
function updatePageLimit(numb, urlnek){
	$.ajax({
	   type: "POST",
	   url: "index.php",
	   data: "node=ashop&page_limit=" + numb,
	   success: function(msg){
			window.location = urlnek;
	   }
	 });
	 
}

