var showMessage = function(title, message) {
	alert(message);
};

var fmt_checked = function(names, anames) {
    if (names.length == 0) {
        return '<font color="#ff0000">Please select: ' + anames.join(',&nbsp;') + '.</font>';
    } else {
        return '<b>Selected: "' + names.join('",&nbsp;"') + '".</b>';
    }
}

var fmt_not_checked = function(anames) {
    return '<font color="#ff0000">Please select: ' + anames.join(',&nbsp;') + '.</font>';
}

var not_checked_notice = function(o, checkeds, attributes) {
	var msg = $('<div></div>');
    var names = [];
    for (var attribute_id in attributes) {
        if (typeof checkeds[attribute_id] == 'undefined') {
            names.push(attributes[attribute_id]['name']);
        }
    }
    msg.addClass(cls_not_checked);
    msg.html(fmt_not_checked(names));
    msg.appendTo($('body'));
    o.bind('mousemove', function(e){
        msg.css('position', 'absolute');
        msg.css('top',  e.clientY + 20);
        msg.css('left', e.clientX);
    }).one('mouseout', function(){
        o.unbind('mousemove');
        msg.remove();
    });
}



var cls_opt_mover   = 'good-attribute-option-mover';
var cls_opt_clicked = 'good-attribute-option-clicked';
var cls_opt_denied  = 'good-attribute-option-denied';

var cls_pic_mover   = 'good-picture-mover';
var cls_pic_clicked = 'good-picture-clicked';

var cls_buy_denied  = 'good-buy-denied';
var cls_not_checked = 'good-buy-not-checked';

var cls_out_of_stock = 'good-out-of-stock';

var cls_review_error = 'furm_remind1';
var cls_big_picture = 'picurl_l';

var box_checked     = '#good_attribute_option_checked';
var box_good_sku    = '#good_sku';
var box_good_title  = '#good_title';
var box_good_price  = '#good_price';
var box_good_market = '#good_market';
var box_good_discount_price = '#good_discount_price';
var box_good_save_rate      = '#good_save_rate';
var box_good_store  = '#good_store';
var box_good_weight = '#good_weight';
var box_good_id     = '#good_id';
var box_product_id  = '#product_id';
var box_quantity    = '#quantity';
var box_picture     = '#picture';
var box_basket_num  = '#basket_num';
var request_url_front    = '#request_url';

var btn_wholesale         = '#wholesale';
var btn_buy               = '#buy';
var btn_quantity_increase = '#quantity_increase';
var btn_quantity_decrease = '#quantity_decrease';

var frm_user_review = '#user_review_form';
var frm_user_inquiry = '#user_inquiry_form';

var addcart_by_form = false;
var form_quantity = '#quantity_1';
var form_submit = '#custom_form';
var chose_store = '#chose_store';
var availability 	= '#availability';
var checkeds = {};
var low_sold_num               = '#low_sold_num';
var cart_current_sold_count    = '#cart_current_sold_count';
var product_attachments = '#product_attachments';

var get_option_selector = function(attribute_id, option_id) {
    return '#good_attribute_' + attribute_id + '_' + option_id;
}

var get_picture_selector = function(picture_id) {
    return '#picture_' + picture_id;
}

$(document).ready(function(){
	
	$(".open_dialog").click(function(){
		$(".dialog_overlay").bgIframe();
		var isIe = $.browser.msie;
		var isIe6 = $.browser.msie && ('6.0' == $.browser.version);
		var dialog = $(".dialog");
		if(dialog.height()<350){
			var fHeight = 350;
		}else{
			var fHeight = dialog.height();
		}
		
		var left = ($(window).width() - dialog.width()) / 2;
		var top = ($(window).height() - fHeight) / 2;
	
		
		dialog.css({top:top+$(document).scrollTop(),left:left+$(document).scrollLeft()});   
		
		
		var ifm = $('.dialog_content');
		var product_inquiry_id = $(box_product_id).val();
		var request_url = $(request_url_front).attr('value');
		ifm.html("loading...");
		ifm.load(url_base + request_url,{"product_id":product_inquiry_id});

		
		if(!isIe6){
						$(".dialog_overlay").css({'width':'100%'})	;
		}else{
						$(".dialog_overlay").css({'width':$(document).width()-20})	;
		}
		 $(".dialog_overlay").css({'left':0, 'top':0,
						'display':'block',
						'height':$(document).height(),
						'z-index':998,
						'position':'absolute'})	;
		dialog.css({'z-index':999, 'display':'block', 'position': 'absolute'});							 
		
	})
	$(".dialog_close").click(function(){
		$(".dialog").removeAttr("style");
		$(".dialog_overlay,.dialog").hide();	
		
	});
});

$(document).ready(function(){
    var checkeds = {};
    var anames  = [];

    var attributes_count = 0;
	
    var bind = function(el) {
        el.bind('mouseover', function(){
            el.addClass(cls_opt_mover);
        }).bind('mouseout', function(){
            el.removeClass(cls_opt_mover);
        }).bind('click', function(){
            var ids = el.attr('id').split('_');
            var attribute_id = ids[2];
            var option_id    = ids[3];
            if (typeof checkeds[attribute_id] != 'undefined' && checkeds[attribute_id] == option_id) {
                el.removeClass(cls_opt_clicked);
                delete checkeds[attribute_id];
            } else {
                if (typeof checkeds[attribute_id] != 'undefined') {
                    $(get_option_selector(attribute_id, checkeds[attribute_id])).removeClass(cls_opt_clicked);
                }
                el.addClass(cls_opt_clicked);
                checkeds[attribute_id] = option_id;
            }
			
            var names = [];
            var checked_count = 0;
            for (var attribute_id in checkeds) {
                var option_id = checkeds[attribute_id];
                names.push(attributes[attribute_id]['options'][option_id]['name']);
                checked_count++;
            }
			
            $(box_checked).html(fmt_checked(names, anames));
			
            var enableds = {};
            for (var attribute_id in attributes) {
                for (var id in goods) {
                    var items = goods[id]['goods_attributeoption_relation_struct']['items'];
                    var r = true;
                    for (var i in checkeds) {
                        if (i != attribute_id && items[i] != checkeds[i]) {
                            r = false;
                            break;
                        }
                    }
                    if (r == true) {
                        if (typeof enableds[attribute_id] == 'undefined') {
                            enableds[attribute_id] = {};
                        }
                        enableds[attribute_id][items[attribute_id]] = true;
                    }
                }
            }
			
            for (var attribute_id in attributes) {
                for (var option_id in attributes[attribute_id]['options']) {
                    var in_checked = (typeof checkeds[attribute_id] != 'undefined' && checkeds[attribute_id] == option_id);
                    var in_enabled = (typeof enableds[attribute_id] != 'undefined' && typeof enableds[attribute_id][option_id] != 'undefined');
                    var item = $(get_option_selector(attribute_id, option_id));
                    unbind(item);
                    if (!in_checked && !in_enabled) {
                        item.attr('disabled', true);
                        item.addClass(cls_opt_denied);
                    } else {
                        bind(item);
                        item.attr('disabled', false);
                        item.removeClass(cls_opt_denied);
                        $(product_attachments).css('display','');
                        $('div[name^="good_attachments"]').css('display','none');
                    }
                }
            }
			
            var gid = 0;
            if (attributes_count == checked_count) {
                for (var id in goods) {
                    var items = goods[id]['goods_attributeoption_relation_struct']['items'];
                    var t = true;
                    for (var attribute_id in items) {
                        var option_id = items[attribute_id];
                        if (typeof checkeds[attribute_id] == 'undefined' || checkeds[attribute_id] != option_id) {
                            t = false;
                            break;
                        }
                    }
                    if (t == true) {
                        gid = id;
                        break;
                    }
                }
                if (gid == 0) {
                    showMessage('Error', 'Internal error.');
                    return false;
                }
            }

            var btn = $(btn_buy);
            if (gid > 0) {
                var good = goods[gid];
                $(box_good_sku).html(good['sku']);
                $(box_good_price).html(currency_sign + good['price']);
                if(good['low_sold_num'] > 1){
                	$(low_sold_num).html("Minimum Purchased Quantity:"+good['low_sold_num']);
                }else{
                	$(low_sold_num).html('');
                }
                $(cart_current_sold_count).val(good['cart_current_sold_count']);
                $(box_good_title).html(good['title']);
                $(box_good_market).html(currency_sign + good['market_price']);
                $(box_good_discount_price).html(currency_sign + good['discount_price']);
                $(box_good_save_rate).html(good['save_rate']);
                if (good['store'] > -1) {
                	$(box_good_store).html(good['store']);
                }
                $(box_good_weight).html(good['weight']);

                $(product_attachments).css('display','none');
                $('div[name="good_attachments_' + gid + '"]').parent().find('div[name^="good_attachments_"]').css('display','none');
                $('div[name="good_attachments_' + gid + '"]').css('display','');
                
				
                if (good['on_sale'] == 1 && good['store'] != 0) {
                    btn.removeClass(cls_out_of_stock);
                } else if (!btn.hasClass(cls_out_of_stock)) {
                    btn.addClass(cls_out_of_stock);
                }
            } else {
				var good = {};
                btn.removeClass(cls_out_of_stock);
            }
			
            $(box_good_id).val(gid);
			if (typeof cbf_good_checked == 'function') {
                cbf_good_checked(el, gid, good);
            }
            if (typeof pictures.length == 'undefined') {
                var picture_ids = {};
                if (gid > 0 && typeof goods[gid] != 'undefined' && typeof goods[gid]['goods_productpic_relation_struct']['items'] != 'undefined') {
                    var items = goods[gid]['goods_productpic_relation_struct']['items'];
                    for (var k = 0; k < items.length; k++) {
                        picture_ids[items[k]] = true;
                    }
                }
                if (typeof pictures_relation.length == 'undefined') {
                    for (var attribute_id in checkeds) {
                        var option_id = checkeds[attribute_id];
                        if (typeof pictures_relation[attribute_id] != 'undefined' && typeof pictures_relation[attribute_id][option_id] != 'undefined') {
                            var items = pictures_relation[attribute_id][option_id];
                            for (var k in items) {
                                picture_ids[items[k]] = true;
                            }
                        }
                    }
                }
				
                var picture_count = 0;
                for (var picture_id in picture_ids) {
                    picture_count ++;
                }
                var is_show = false;
                var picture_relation_count = 0;
                for (var picture_id in pictures) {
                    var picture = $(get_picture_selector(picture_id));
                    if (picture_count == 0 || typeof picture_ids[picture_id] != 'undefined') {
                        picture.show();
                        picture_relation_count++;
                    }
                    if (picture_count > 0 && typeof picture_ids[picture_id] == 'undefined') {
                        picture.hide();
                    }
                }
                if (typeof cbf_opt_click == 'function') {
                	cbf_opt_click(el, gid, picture_relation_count);
                }
                var first_picture   = null;
                var default_picture = null;
                for (var picture_id in pictures) {
                    var picture = $(get_picture_selector(picture_id));
                    if (picture.is(':visible')) {
                        if (first_picture == null) {
                            first_picture = picture;
                        }
                        if (default_picture_id == picture_id) {
                            default_picture = picture;
                        }
                    }
                }
                if (default_picture != null) {
                    default_picture.click();
                } else if (first_picture != null) {
                    first_picture.click();
                }
            } else {
            	if (typeof cbf_opt_click == 'function') {
            		cbf_opt_click(el, gid, 0);
            	}
            }
            
            if($(availability).length > 0)
            {
                if($(box_good_id).val() == 0 )
                {
                	$(availability).html("");
                	$(low_sold_num).html("");
                }else{
                	if(goods[$(box_good_id).val()]['store'] != -1)
                	{
                		$(availability).html("Store:"+goods[$(box_good_id).val()]['store']);
                	}else{
                		$(availability).html("Adequate stock.");
                	}
                }
            }
            
        });
    }
    
    var unbind = function(el) {
        el.unbind('mouseover').unbind('mouseout').unbind('click');
    }
    
    if (typeof attributes.length == 'undefined') {
        for (var attribute_id in attributes) {
            attributes_count++;
            anames.push(attributes[attribute_id]['name']);
            for (var option_id in attributes[attribute_id]['options']) {
                bind($(get_option_selector(attribute_id, option_id)));
            }
        }
    }
    
    if (typeof pictures.length == 'undefined') {
        for (var picture_id in pictures) {
            $(get_picture_selector(picture_id)).bind('click', function(){
                for (var id in pictures) {
                    $(get_picture_selector(id)).removeClass(cls_pic_clicked);
                }
                $(this).addClass(cls_pic_clicked);
                var id = $(this).attr('id').split('_')[1];
                if (typeof pictures[id] != 'undefined') {
                    var picture = $(box_picture);
                    picture.attr('src',   pictures[id][cls_big_picture]);
                    picture.attr('title', pictures[id]['title']);
                    picture.parent().attr('href', pictures[id]['picurl_o']);
                } else {
                    showMessage('Error', 'Internal error.');
                    return false;
                }
            }).bind('mouseover', function(){
                $(this).addClass(cls_pic_mover);
            }).bind('mouseout', function(){
                $(this).removeClass(cls_pic_mover);
            });
        }
    }
    $(btn_buy).bind('mouseover', function(){
        var good_id = $(box_good_id).val();
        if (good_id == 0) {
        	not_checked_notice($(this), checkeds, attributes);
        	return false;
        }
		if(goods[$(box_good_id).val()]['on_sale'] == 1 && $(box_good_id).val() != 0 && $(chose_store).length>0)
		{
			var n = $(box_quantity).val();
	        var good_store = goods[$(box_good_id).val()]['store'];
	        
	        if(good_store== -1)
	        {
	        	$(chose_store).hide();
	        }else if(good_store<n && good_store){
	        	$(chose_store).html('The stock is inadequate for purchased commodities.').show();
	        }else{
	        	$(chose_store).hide();
	        }
	        
	        //��С������
	        var low_sold_num = goods[$(box_good_id).val()]['low_sold_num'];
	        var cart_current_sold_count = goods[$(box_good_id).val()]['cart_current_sold_count'];
	        v = low_sold_num - cart_current_sold_count;
	        if(v>n && low_sold_num && good_store){
	        	$(chose_store).html('Purchased commodities quantity is less than required minimum.').show();
	        }
		}
    }).bind('click', function(){
		if($(box_good_id).val() != 0)
		{
			var n = $(box_quantity).val();
	        var good_store = goods[$(box_good_id).val()]['store'];
	        if(good_store != -1 && good_store < n)
	        {
	        	return false;
	        }
	        
	        var good_low_sold_num = goods[$(box_good_id).val()]['low_sold_num'];
			var cart_current_sold_count = goods[$(box_good_id).val()]['cart_current_sold_count'];
	        v = good_low_sold_num - cart_current_sold_count;
	        if($(low_sold_num).length && good_low_sold_num && v > n)
	        {
	        	return false;
	        }
		}
    	
        var good_id = $(box_good_id).val();
    	
        if (typeof goods[good_id] != 'undefined' && goods[good_id]['on_sale'] == 1) {
            var product_id = $(box_product_id).val();
            var quantity = $(box_quantity).val();
            if (quantity == 0 || quantity == '') {
                quantity = 1;
            }
            if (goods[good_id]['store'] == 0) {
            	return false;
            }
            if (goods[good_id]['store'] > 0 && goods[good_id]['store'] < quantity) {
            	quantity = goods[good_id]['store'];
            }

            if (typeof addcart_by_ajax != 'undefined' && addcart_by_ajax == true) {
            	if (typeof before_form_submit == 'function') {
            		before_form_submit();
                }
            	$.ajax({
            		url: url_base + 'cart/static_cart_add',
            		type: 'POST',
            		data: 'product_id=' + product_id + '&good_id=' + good_id + '&quantity=' + quantity,
            		dataType: 'json',
            		success: function(retdat, status){
            			if (retdat['code'] == 200 && status == 1) {
            				$(btn_basket_num).val(retdat['content']['quantity']);
            				showMessage('Success', retdat['msg']);
            			} else {
            				showMessage('Failed', retdat['msg']);
            			}
            		},
            		error: function(){
            			showMessage('Error', 'Request error, please try again later!');
            		}
            	});
            } else if(typeof addcart_by_form != 'undefined' && addcart_by_form == true){
            	if (typeof before_form_submit == 'function') {
            		before_form_submit();
                }
    			$(form_submit).submit();
            } else {
            	if (typeof before_form_submit == 'function') {
            		before_form_submit();
                }
            	location.href = url_base + 'cart/add/' + product_id + '/' + good_id + '/' + quantity;
            }
            $(this).unbind('click');
        }       
    });
    
    $(box_quantity).bind('keydown', function(e){
        var keyNum = e.keyCode;
        return (keyNum == 8 || keyNum == 46 || keyNum == 18 || keyNum == 9 ||
        keyNum == 37 || keyNum == 39 || 
        (keyNum-48 <= 9 &&  0 <= keyNum-48) || (keyNum-96 <= 9 &&  0 <= keyNum-96)) && !e.shiftKey;
    }).bind('keyup', function(){
        var reg = /[^\d]/g;
        if(reg.test($(this).val()))
        {
            $(this).val($(this).val().replace(reg,""));
        }
    });
    
    $(btn_quantity_increase).bind('click', function(){
        var count = $(box_quantity).val();
        if (count == '') {
            count = 1;
        } else {
            count ++;
        }
        $(box_buy_count).val(count);
    });
	
    $(btn_quantity_decrease).bind('click', function(){
        var count = $(box_quantity).val();
        if (count == '') {
            count = 1;
        } else if (count > 1) {
            count --;
        }
        $(box_buy_count).val(count);
    });

    if (typeof $(frm_user_review).validate == 'function') {
	    $(frm_user_review).validate({
	        errorClass: cls_review_error,
	        rules:{
	    		user_first_name:{
	    			required:true,
	    			maxlength:50
	    		},
	    		user_last_name:{
	    			required:true,
	    			maxlength:50
	    		},
	    		user_email:{
	    			required:true,
	    			maxlength:320,
	    			email:true
	    		},
	    		user_message:{
	    			required:true,
	    			maxlength:65535
	    		},
                secode: {
                    required: true,
                    remote: '/user_do_secode?name=comment'
                }
	    	},
            messages: {
                    secode: {
                        remote: "Secode wrong."
                    }
             },
	        submitHandler: function(form) {
	            try {
	            	if (typeof addcomment_by_ajax == 'undefined') {
	            		addcomment_by_ajax = true;
	            	}
	            	if (addcomment_by_ajax == true) {
		                $.ajax({
		                    url: $(form).attr('action'),
		                    type: 'POST',
		                    data: $(form).serialize(),
		                    dataType: 'json',
		                    success: function(retdat, status) {
		                		form.reset();
		                		$('input[name=token]').val(retdat['content']['token']);
		                        if (retdat['code'] == 200 && retdat['status'] == 1) {
		                            showMessage('Success', retdat['msg']);
		                        } else {
		                        	showMessage('Failed', retdat['msg']);
		                        }
		                    },
		                    error: function() {
		                    	showMessage('Error', 'Request error, please try again later!');
		                    }
		                });
	            	} else {
	            		$(form).get(0).submit();
	            	}
	            } catch (ex) {}
	            return false;
	        }
	    });
    }

    if (typeof $(frm_user_inquiry).validate == 'function') {
	    $(frm_user_inquiry).validate({
	        errorClass: cls_review_error,
	        rules:{
	    		user_name:{
	    			required:true,
	    			maxlength:50
	    		},
	    		content:{
	    			required:true,
	    			maxlength:1024
	    		},
	    		email:{
	    			required: true,
	    			email:true,
                    remote: '/productinquiry/check_email?product_id='+$(box_product_id).val()
	    		},
                secode: {
                    required: true,
                    remote: '/user_do_secode?name=inquiry'
                }
	    	},
            messages: {
                    secode: {
                        remote: "Secode wrong."
                    }
             },
	        submitHandler: function(form) {
	            try {
	            	if (typeof addinquiry_by_ajax == 'undefined') {
	            		addinquiry_by_ajax = true;
	            	}
	            	if (addinquiry_by_ajax == true) {
		                $.ajax({
		                    url: $(form).attr('action'),
		                    type: 'POST',
		                    data: $(form).serialize(),
		                    dataType: 'json',
		                    success: function(retdat, status) {
		                		form.reset();
		                		$('input[name=token]').val(retdat['content']['token']);
		                        if (retdat['code'] == 200 && retdat['status'] == 1) {
		                            showMessage('Success', retdat['msg']);
		                        } else {
		                        	showMessage('Failed', retdat['msg']);
		                        }
		                    },
		                    error: function() {
		                    	showMessage('Error', 'Request error, please try again later!');
		                    }
		                });
	            	} else {
	            		$(form).get(0).submit();
	            	}
	            } catch (ex) {}
	            return false;
	        }
	    });
    }
    
    if (typeof attributes.length != 'undefined' && (on_sale == 0 || goods[$(box_good_id).val()]['store'] == 0)) {
    	if (!$(btn_buy).hasClass(cls_out_of_stock)) {
    		$(btn_buy).addClass(cls_out_of_stock);
    	}
    }
    
    var gid = $(box_good_id).val();
    if (typeof goods[gid] != 'undefined' && typeof goods[gid]['goods_attributeoption_relation_struct'] != 'undefined' && typeof goods[gid]['goods_attributeoption_relation_struct']['items'] != 'undefined') {
    	if (goods[gid]['on_sale'] == 0 || goods[gid]['store'] == 0) {
        	for (var nid in goods) {
        		if (goods[nid]['on_sale'] == 1 && goods[nid]['store'] != 0) {
        			gid = nid;
        			break;
        		}
        	}
        }
    	var items = goods[gid]['goods_attributeoption_relation_struct']['items'];
        for (var attribute_id in items) {
            $(get_option_selector(attribute_id, items[attribute_id])).click();
            
        }
    }
    
    return false;
});

