/** 
 * @file thangiswho.2en.js
 * @author ThangisWho
 **/

var meeboWindow = null;

function meeboPopOut() {
	if (meeboWindow == null || meeboWindow.closed ) {
		meeboWindow = window.open("/_chat.html","meeboPopout","toolbar=no,directories=no,status=no,menubar=no,resizable=0,location=no,width=320,height=400");
	}
	else {
		
	}
	
	meeboWindow.focus();
	return false;
}

function toggleMenu(el, over)
{
    if (over) {
        $jQ(el).addClass('over');
    }
    else {
        $jQ(el).removeClass('over');
    }
}
function toggleDD(did) {
	$jQ('#filterDD_'+did).toggleClass('no-display');
}
function toggleActive(o){
	$jQ(o).toggleClass('ui-state-active');
}
function mainContent2en(u) {
	u = u.replace(/([?&])noLeft=[^&]*/, '$1');
	u = u.replace(/[?&]$/, '');
	gotoPosition('#bodyContent');
	gotoHash(u,'!');
}

function remove_attribute_value(aid){
	var elem = document.getElementById('th' + aid);
	var ary = elem.getElementsByTagName("a");
	for(var i=0;i < ary.length;i++){
		$(ary[i].id).removeClassName("ui-state-default").addClassName('ui-state-disabled').removeClassName('active');
	}
}
function set_attribute_value( attribute_id, val, curr_id) {
	if ( $(curr_id).hasClassName('ui-state-disabled') )
		return false;
	
	var elem = document.getElementById('thattribute' + attribute_id);
	var ary = elem.getElementsByTagName("a");
	for(var i=0;i < ary.length;i++){
		if(ary[i].id == curr_id ) {
			$(ary[i].id).addClassName("active");
		}
		else{
			$(ary[i].id).removeClassName("active");
		}
	}

	dropdown = document.getElementById('attribute' + attribute_id);
	for ( var i = 0; i < dropdown.options.length; i++ ) {
		if ( dropdown.options[i].value == val ) {
			dropdown.selectedIndex = i;
			break;
		}
	}
	spConfig.configureElement($('attribute' + attribute_id));
	spConfig.reloadPrice();
}
function set_custom_attr_value(sb_id,val,curr_id){
	cont = 'thselect_'+sb_id;
	sb_cont = 'select_'+sb_id;
	
	var elem = document.getElementById(cont);
	var ary = elem.getElementsByTagName("a");
	for(var i=0;i < ary.length;i++){
		if(ary[i].id == curr_id){
			$(ary[i].id).addClassName("active");
		}
		else{
			$(ary[i].id).removeClassName("active");
		}
	}
	
	dropdown = document.getElementById(sb_cont);
	for ( var i = 0; i < dropdown.options.length; i++ ) {
	   if ( dropdown.options[i].value == val ) {
			dropdown.selectedIndex = i;
			 break;
		}
	 }

	opConfig.reloadPrice();
}

function do2en2(a){
	$jQ('.thangiswho').each(function(){
		var o = $jQ(this);
		o.data( 'thangiswho', {
			cache: {
				'': o
			}
		});
	});
  
	$jQ('.thangiswhoContent a[href^=#]').live( 'click', function(e){
    	var state = {},
    	id = $(this).closest( '.thangiswhoContent' ).attr( 'id' ),
    	url = $(this).attr( 'href' ).replace( /^#/, '' );
    
	    // Set the state!
	    state[ id ] = url;
	    $.bbq.pushState( state );
    
    	return false;
 	});
  
	$jQ(window).bind( 'hashchange', function(e) {
    	$('.thangiswho').each(function(){
			var that = $(this),
			data = that.data( 'thangiswho' ),
			u = e.getState( that.attr( 'id' ) ) || '';
      
			// If the url hasn't changed, do nothing and skip to the next .bbq widget.
			if ( data.url === u ) { return; }
			data.url = u;
			// Hide any visible ajax content.
			that.find( '.thangiswhoContent' ).children( ':visible' ).hide();
			
			if ( data.cache[ u ] ) {
				data.cache[ u ].show();
			} else {
				showLoading(1);
				data.cache[ u ] = $( '<div class="thangiswho-item"/>' )
				.appendTo( that.find( '.thangiswhoContent' ) )
				.load( url, function(){
					doGA(u);
					hideLoading();
				});
			}
		});
	})

	$jQ(window).trigger( 'hashchange' );
}
(function ($) {
	//get2en
	$.fn.get2en = function(isHyper,cb,s) {
		this.each(function(){
			var o = $(this);
			if ( o.hasClass('noAjax') )
				return;
			
			var u = o.attr('href').replace(/([?&])(noLeft|thAjax)=[^&]*/, '$1');
			u = u.replace(/[?&]$/, '');
			o.attr('href',u);
			o.click(function(e){
				e.preventDefault();
				if (isHyper) gotoPosition('#bodyContent');
				if (cb) cb(o);
				gotoHash(u,'!',s);
				return false;
			});
		})
		return this;
	}; //ends get2en
	
	//thLightBox2en
	$.fn.thLightBox2en = function(options) {
		var options = $.extend({
			width:910, type:'lightbox'
		},options);
		
		this.each(function(){
			var o = $(this);
			var u = o.attr('href').replace(/([?&])(noLeft|thAjax)=[^&]*/, '$1');
			u = u.replace(/[?&]$/, '');
			o.attr('href',u);
			o.click(function(e){
				e.preventDefault();
				gotoHash(u,'!', (options.type == 'popup') ? '!pu' : '!lb');
				return false;
			});
		})
		return this;
	}; //ends thLightBox2en
	
	//thAddToCart
	$.fn.thAddToCart = function(u,no) {
		this.each(function(){
			var f = $(this);
			var params = f.formSerialize() + '&thAjax=1';
			if (no) params += '&thForce=1';
			
			var d = $jQ('#dialogCart');
			if (d) d.remove();
			f.prepend('<div id="dialogCart"></div>');
			d = $jQ('#dialogCart');
			showLoading(true);
                        
			$.post(u, params, function(data) {
				if ( data.confirm ) {
					d.html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:3px 7px 50px 5px;"></span> '+data.message+'</p>');
					var btn = data.button || 'OK';
					d.dialog({
						title: data.title,
						resizable:false,
						modal: true,
						width: 400,
						buttons:{
							OK: function(){ $(this).dialog("destroy"); f.thAddToCart(u,1); },
							Cancel: function(){ $(this).dialog("destroy");}
						},
						close: function(e,ui) {$(this).dialog( "destroy" );}
					});      
				}
				else {
					var mark = ( data.status ) ? 'check' : 'close';
					d.html('<p><span class="ui-icon ui-icon-circle-'+mark+'" style="float:left; margin:3px 7px 50px 5px;"></span> '+data.message+'</p>');
					d.dialog({
						title: data.title,
						resizable:false,
						modal: true,
						width: 400,
						buttons:{
							' Tiếp tục mua hàng ': function(){ $(this).dialog("destroy");},
                            ' Tiến hành đặt hàng ': function(){ $(this).dialog("destroy"); window.location.href="/nu/checkout/cart/"; }
						}
					});
				}
				
				hideLoading();
				doGA(u);
			}, 'json');
		});
		
		return false;
	};//ends thAddToCart
	
})(jQuery);

var TH_IE_VERSION = 0;
jQuery(document).ready(function($) {
	if ( f_is() ) {
		f_png();
		$jQ('#meeboWidget2').css({position:'absolute'}).remove();
		$jQ('.search_box').find('.left, .input, .button').each(function(){
			f_div($jQ(this));
		});
		$jQ('.oneContent').find('#left, #right, #center').each(function(){
			f_div($jQ(this));
		});
		//$jQ('#main_menu').thMenu();
	}
});

function f_is() {
	var arVersion = navigator.appVersion.split("MSIE");
	if (! (arVersion && arVersion[1]) ) return false;
	TH_IE_VERSION = parseInt(arVersion[1]);

	if ( TH_IE_VERSION <7 && (document.body.filters) )
		return true;
	return false;
}
function f_div(o) {
	var bgIMG = o.css('background-image');
		if(bgIMG && bgIMG.indexOf(".png")!=-1){
			var iebg = bgIMG.split('url("')[1].split('")')[0];
			o.css('background-image', 'none');
			o.get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
		}
}
function f_png() {
	for(var i=0; i<document.images.length; i++)
	{
		var img = document.images[i];
		var imgName = img.src.toUpperCase();
		if ( imgName.substring(imgName.length-3, imgName.length) == "PNG" )
		{
			var imgID = (img.id) ? "id='" + img.id + "' " : "";
			var imgClass = (img.className) ? "class='" + img.className + "' " : "";
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
			var imgStyle = "display:inline-block;" + img.style.cssText ;
			if (img.align == "left") imgStyle = "float:left;" + imgStyle;
			if (img.align == "right") imgStyle = "float:right;" + imgStyle;
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='crop');\"></span>" ;
			img.outerHTML = strNewHTML;
			i = i-1;
		}
	}
}

/**************************** CONFIGURABLE PRODUCT **************************/
if(typeof Product=='undefined') {
    Product = {};
}
Product.ThConfig = Class.create();
Product.ThConfig.prototype = {
    initialize: function(config){
        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        if (config.containerId) {
            this.settings   = $$('#' + config.containerId + ' ' + '.super-attribute-select');
        } else {
            this.settings   = $$('.super-attribute-select');
        }
        this.state      = new Hash();
        this.priceTemplate = new Template(this.config.template);
        this.prices     = config.prices;
        
        // Set default values from config
        if (config.defaultValues) {
            this.values = config.defaultValues;
        }
        
        // Overwrite defaults by url
        /*var separatorIndex = window.location.href.indexOf('#');
        if (separatorIndex != -1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            var urlValues = paramsStr.toQueryParams();
            if (!this.values) {
                this.values = {};
            }
            for (var i in urlValues) {
                this.values[i] = urlValues[i];
            }
        }*/
        
        // Overwrite defaults by inputs values if needed
        if (config.inputsInitialized) {
            this.values = {};
            this.settings.each(function(element) {
                if (element.value) {
                    var attributeId = element.id.replace(/[a-z]*/, '');
                    this.values[attributeId] = element.value;
                }
            }.bind(this));
        }
            
        // Put events to check select reloads 
        this.settings.each(function(element){
            Event.observe(element, 'change', this.configure.bind(this))
        }.bind(this));

        // fill state
        this.settings.each(function(element){
            var attributeId = element.id.replace(/[a-z]*/, '');
            if(attributeId && this.config.attributes[attributeId]) {
                element.config = this.config.attributes[attributeId];
                element.attributeId = attributeId;
                this.state[attributeId] = false;
            }
        }.bind(this))

        // Init settings dropdown
        var childSettings = [];
        for(var i=this.settings.length-1;i>=0;i--){
            var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
            var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
            if (i == 0){
                this.fillSelect(this.settings[i])
            } else {
                this.settings[i].disabled = true;
            }
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;
            childSettings.push(this.settings[i]);
        }

        // Set values to inputs
        this.configureForValues();
        document.observe("dom:loaded", this.configureForValues.bind(this));
    },
    
    configureForValues: function () {
        if (this.values) {
            this.settings.each(function(element){
                var attributeId = element.attributeId;
                element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
                this.configureElement(element);
            }.bind(this));
        }
    },

    configure: function(event){
        var element = Event.element(event);
        this.configureElement(element);
    },

    configureElement : function(element) {
        this.reloadOptionLabels(element);
        if(element.value){
            this.state[element.config.id] = element.value;
            if(element.nextSetting){
                element.nextSetting.disabled = false;
                this.fillSelect(element.nextSetting);
                this.resetChildren(element.nextSetting);
            }
        }
        else {
            this.resetChildren(element);
        }
        this.reloadPrice();
    },

    reloadOptionLabels: function(element){
        var selectedPrice;
        if(element.options[element.selectedIndex].config && !this.config.stablePrices){
            selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
        }
        else{
            selectedPrice = 0;
        }
        for(var i=0;i<element.options.length;i++){
            if(element.options[i].config){
                element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
            }
        }
    },

    resetChildren : function(element){
        if(element.childSettings) {
            for(var i=0;i<element.childSettings.length;i++){
                element.childSettings[i].selectedIndex = 0;
                element.childSettings[i].disabled = true;
                if(element.config){
                    this.state[element.config.id] = false;
                }
            }
        }
    },

    fillSelect: function(element){
        var attributeId = element.id.replace(/[a-z]*/, '');
        var options = this.getAttributeOptions(attributeId);
        this.clearSelect(element);
        element.options[0] = new Option(this.config.chooseText, '');

        var prevConfig = false;
        if(element.prevSetting){
            prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
        }

        if(options) {
            var index = 1;
            for(var i=0;i<options.length;i++){
                var allowedProducts = [];
                if(prevConfig) {
                    for(var j=0;j<options[i].products.length;j++){
                        if(prevConfig.config.allowedProducts
                            && prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
                            allowedProducts.push(options[i].products[j]);
                        }
                    }
                } else {
                    allowedProducts = options[i].products.clone();
                }

                if(allowedProducts.size()>0){
                    options[i].allowedProducts = allowedProducts;
                    element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
                    if (typeof options[i].price != 'undefined') {
                        element.options[index].setAttribute('price', options[i].price);
                    }
                    element.options[index].config = options[i];
                    index++;

                    $('attr_'+options[i].id).removeClassName('ui-state-disabled').addClassName('ui-state-default');
                }
            }
        }
    },

    getOptionLabel: function(option, price){
        var price = parseFloat(price);
        if (this.taxConfig.includeTax) {
            var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
            var excl = price - tax;
            var incl = excl*(1+(this.taxConfig.currentTax/100));
        } else {
            var tax = price * (this.taxConfig.currentTax / 100);
            var excl = price;
            var incl = excl + tax;
        }

        if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
            price = incl;
        } else {
            price = excl;
        }

        var str = option.label;
        if(price){
            if (this.taxConfig.showBothPrices) {
                str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
            } else {
                str+= ' ' + this.formatPrice(price, true);
            }
        }
        return str;
    },

    formatPrice: function(price, showSign){
        var str = '';
        price = parseFloat(price);
        if(showSign){
            if(price<0){
                str+= '-';
                price = -price;
            }
            else{
                str+= '+';
            }
        }

        var roundedPrice = (Math.round(price*100)/100).toString();

        if (this.prices && this.prices[roundedPrice]) {
            str+= this.prices[roundedPrice];
        }
        else {
            str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
        }
        return str;
    },

    clearSelect: function(element){
    	remove_attribute_value(element.id);
        for(var i=element.options.length-1;i>=0;i--){
            element.remove(i);
        }
    },

    getAttributeOptions: function(attributeId){
        if(this.config.attributes[attributeId]){
            return this.config.attributes[attributeId].options;
        }
    },

    reloadPrice: function(){
        if (this.config.disablePriceReload) {
            return;
        }
        var price    = 0;
        var oldPrice = 0;
        for(var i=this.settings.length-1;i>=0;i--){
            var selected = this.settings[i].options[this.settings[i].selectedIndex];
            if(selected.config){
                price    += parseFloat(selected.config.price);
                oldPrice += parseFloat(selected.config.oldPrice);
            }
        }

        optionsPrice.changePrice('config', {'price': price, 'oldPrice': oldPrice});
        optionsPrice.reload();

        return price;

        if($('product-price-'+this.config.productId)){
            $('product-price-'+this.config.productId).innerHTML = price;
        }
        this.reloadOldPrice();
    },

    reloadOldPrice: function(){
        if (this.config.disablePriceReload) {
            return;
        }
        if ($('old-price-'+this.config.productId)) {

            var price = parseFloat(this.config.oldPrice);
            for(var i=this.settings.length-1;i>=0;i--){
                var selected = this.settings[i].options[this.settings[i].selectedIndex];
                if(selected.config){
                    price+= parseFloat(selected.config.price);
                }
            }
            if (price < 0)
                price = 0;
            price = this.formatPrice(price);

            if($('old-price-'+this.config.productId)){
                $('old-price-'+this.config.productId).innerHTML = price;
            }

        }
    }
}
