﻿var rootPath = "";
var resourcePath = "";
var modelID = "";

var pricechart_time;
var salechart_time;
var popchart_time;
var shopchart_time;


function errImg() {
  return "<img src='" + resourcePath + "/img/error.png' style='vertical-align:middle'/>";
}

function successImg() {
  return "<img src='" + resourcePath + "/img/tick_circle.png' style='vertical-align:middle'/>";
}

function FC_Rendered(DOMId){
	var chartObj = getChartFromId(DOMId);
	var chartUrl = rootPath + "/" + DOMId + ".html";
	
	var param="?modelID=" + modelID + "&t="+new Date().getTime()+"&time="+eval(DOMId + "_time");
	chartObj.setDataURL(escape(chartUrl+param));
}

function initChart(chart, divID) {
	chart.setDataXML("<chart></chart>");
	chart.render(divID);
}

function setChartUrl(linkObj, chartID, time){
	var o=$(linkObj);
	$('a', o.parent()).removeClass("t_highlight");
	o.addClass("t_highlight");
	
	if (chartID=='pricechart') pricechart_time=time;
	if (chartID=='salechart') salechart_time=time;
	if (chartID=='popchart') popchart_time=time;
	if (chartID=='shopchart') shopchart_time=time;
		
	FC_Rendered(chartID);
}

function initChartTabs() {
	var cw="863";
   var ch="180";
   
   var pc = new FusionCharts(resourcePath + "/charts/MSLine.swf", "pricechart", cw, ch, "0", "1");
   initChart(pc, "p_chart");
   
   var lineFlashUrl = resourcePath + "/charts/Line.swf";
   var sc = new FusionCharts(lineFlashUrl, "salechart", cw, ch, "0", "1");
   initChart(sc, "s_chart");
   
   //var popc = new FusionCharts(lineFlashUrl, "popchart", cw, ch, "0", "1");
   //initChart(popc, "o_chart");
   
   var oc = new FusionCharts(lineFlashUrl, "shopchart", cw, ch, "0", "1");
   initChart(oc, "h_chart");
}

function initDetailTabs() {
	 $("#detail_tabs").tabs({ 
		select: function(event, ui) {
	        var ref = $(ui.panel).attr('ref');
	        if (ref) {
	        	window.location.hash=ref;
	        }
	    },
	    idSuffix: '_gl',
		cache:true,
		spinner:'<em><img src="' + resourcePath + '/img/loading.gif" style="vertical-align:middle;width:16px;height:16px"/> 正在加载&#8230;</em>' 
	}).show();
}

function selectDetailTab(index, noscroll) {
	$('#detail_tabs').tabs('select', index);
	if (noscroll) {
		//do nothing
	} else {
		window.scrollTo(0, 300);
	}
}

function initPhotoGallery() {
	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;
	$('#thumbs-adv ul.thumbs li').css('opacity', onMouseOutOpacity)
		.hover(
			function () {
				$(this).not('.selected').fadeTo('fast', 1.0);
			}, 
			function () {
				$(this).not('.selected').fadeTo('fast', onMouseOutOpacity);
			}
		);
	
	$(function() {
		// Initialize Advanced Galleriffic Gallery
		var galleryAdv = $('#gallery-adv').galleriffic('#thumbs-adv', {
			delay:                  2000,
			numThumbs:              12,
			preloadAhead:           2,
			enableTopPager:         true,
			enableBottomPager:      true,
			imageContainerSel:      '#slideshow-adv',
			controlsContainerSel:   '#controls-adv',
			captionContainerSel:    '#caption-adv',
			loadingContainerSel:    '#loading-adv',
			renderSSControls:       true,
			renderNavControls:      true,
			playLinkText:           '幻灯片播放',
			pauseLinkText:          '停止播放',
			prevLinkText:           '&lsaquo; 上一图片',
			nextLinkText:           '下一图片 &rsaquo;',
			nextPageLinkText:       '&rsaquo;',
			prevPageLinkText:       '&lsaquo;',
			enableHistory:          true,
			autoStart:              false,
			onChange:               function(prevIndex, nextIndex) {
				$('#thumbs-adv ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);
			},
			onTransitionOut:        function(callback) {
				$('#slideshow-adv, #caption-adv').fadeOut('fast', callback);
			},
			onTransitionIn:         function() {
				$('#slideshow-adv, #caption-adv').fadeIn('fast');
			},
			onPageTransitionOut:    function(callback) {
				$('#thumbs-adv ul.thumbs').fadeOut('fast', callback);
			},
			onPageTransitionIn:     function() {
				$('#thumbs-adv ul.thumbs').fadeIn('fast');
			}
		});
	});
}

function submitComplain(){
	if ($('#complain_txt').attr('value')=='') {
		$('#complain_error').show().html(errImg()+'请输入内容。');
		$('#complain_txt').focus();
		return false;
	}
	$.ajax({
        url: rootPath + "/a.do", 
        data: $('#complain_form').serialize(),
        dataType: "json",
        type: 'POST', 
        beforeSend: function() {
           	$('#complain_error').hide();
            $('#complain_loading').show();
            $('#complain_submit_btn').attr('disabled','true');
        },
        error: function(request) {
            $('#complain_loading').hide();
            $('#complain_submit_btn').removeAttr("disabled");
            $('#complain_error').show().html(errImg()+'发表抱怨时发生服务器错误。');
        },
        success: function(data) {
        	$("#complain_loading").hide();
            if (data.ok) {
            	window.location.reload();
            } else {
            	$('#complain_submit_btn').removeAttr("disabled");
            	$('#complain_error').show().html(errImg()+'发表抱怨出错。');
            }
        }
    });
    return false;
}

function initAddComplainDlg() {
	$(function() {
		$('a.complain_btn').cluetip({
		  cursor:'',
		  ajaxCache: false,
		  width: 400,
		  arrows: true, 
		  dropShadow: true,
		  hoverIntent: false,
		  sticky: true,
		  mouseOutClose: false,
		  closePosition: 'title',
		  activation: 'click',
		  closeText: '<img src="' + resourcePath + '/img/cross.png" title="关闭" />',
		  cluetipClass: 'jtip'
		});
	});
}

function initShowComplainDlg() {
	$(function() {
		$('a.show_complain').cluetip({
		  cursor:'',
		  ajaxCache: false,
		  width: 400,
		  arrows: true, 
		  dropShadow: true,
		  hoverIntent: false,
		  sticky: false,
		  mouseOutClose: false,
		  closePosition: 'title',
		  cluetipClass: 'jtip'
		});
	});
}

function initCommentFormAction() {
	$('#comment_form').submit(function(){
		var scoreList = "";
		var i;
		var hasScore=false;
		for(i=0;i<earr.length;i++){
		scoreList+=earr[i]+":"+varr[i]+";";
		if(varr[i]>0)hasScore=true;
		}
		if (satis_v <= 0 || !hasScore) {
			$('#comment_error').show().html(errImg()+'必须点击左侧的空白五角星进行评分。');
			return false;
		}
		scoreList+="-1:" + satis_v;
		if ($('#cmt_area').attr('value')=='' && $('#adv_area').attr('value')=='' && $('#defect_area').attr('value')=='') {
			$('#comment_error').show().html(errImg()+'必须输入“优点”，“缺点”或“总结”至少一条评价内容。');
			return false;
		}
		$('#score_list').attr('value',scoreList);
		$.ajax({
	        url: rootPath + '/a.do', 
	        data: $('#comment_form').serialize(),
	        dataType: "json",
	        type: 'POST', 
	        beforeSend: function() {
	           	$('#comment_error').hide();
	            $('#comment_loading').show();
	            $('#cmt_submit_btn').attr('disabled','true');
	        },
	        error: function(request) {
	            $('#comment_loading').hide();
	            $('#cmt_submit_btn').removeAttr("disabled");
	            $('#comment_error').show().html(errImg()+'发表评价时发生连接错误。');
	        },
	        success: function(data) {
	        	$("#comment_loading").hide();
	        	if (data.ok) {
	            	window.location.reload();
	            } else {
	            	$('#cmt_submit_btn').removeAttr("disabled");
	            	$('#comment_error').show().html(errImg()+'发表评价出错。');
	            }
	        }
	    });
	    return false;
	});
}

function submitSubscription(){
	if($('#price_cb').attr('checked')) {
		var _price=$('#price_input').attr('value');
		if (_price=='') {
			$('#subscription_error').show().html(errImg()+'请输入价格。');
			$('#price_input').focus();
			return false;
		}
		$('#subs_content').attr('value', "PRICE|" + _price);
	}
	$.ajax({
        url: rootPath + "/a.do", 
        data: $('#subscription_form').serialize(),
        dataType: "json",
        type: 'POST', 
        beforeSend: function() {
           	$('#subscription_error').hide();
            $('#subscription_loading').show();
            $('#subscription_submit_btn').attr('disabled','true');
        },
        error: function(request) {
            $('#subscription_loading').hide();
            $('#subscription_submit_btn').removeAttr("disabled");
            $('#subscription_error').show().html(errImg()+'添加关注时发生服务器错误。');
        },
        success: function(data) {
        	$("#subscription_loading").hide();
            if (data.ok) {
            	$('#cluetip').hide();
            	$('#favorite_new').hide();
            	$('#favorite_exists').show();
            } else {
            	$('#subscription_submit_btn').removeAttr("disabled");
            	$('#subscription_error').show().html(errImg()+'添加关注出错。');
            }
        }
    });
    return false;
}

function fetchCompareBox() {
	$.ajax({
        url: rootPath + "/compare_box.html", 
        type: "GET",
        success: function(data) {
        	$('#compare_box').show().html(data);
        }
    });
}

function fetchLoginDlg() {
	$.ajax({
        url: rootPath + "/login_dlg.html", 
        type: "GET",
        success: function(data) {
        	$('#login_dlg').html(data);
        }
    });
}

$.ajaxSetup({cache:false});

$(function() {
	$("#shop_table tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");})
    $("#shop_table tr:even").addClass("alt");
	
	var url = rootPath + '/a.do?a=update_vc&p1=model&p2=' + modelID;
	$.getJSON(url, function(j){
        if (j.ok){ } else{ }
    });
	
	//subscription
	$('a.subscription_btn').cluetip({
	  cursor:'',
	  ajaxCache: false,
	  width: 400,
	  arrows: true, 
	  dropShadow: true,
	  hoverIntent: false,
	  sticky: true,
	  mouseOutClose: false,
	  closePosition: 'title',
	  activation: 'click',
	  closeText: '<img src="' + resourcePath + '/img/cross.png" title="关闭" />',
	  cluetipClass: 'jtip',
	  onShow: function(ct, c){
		$('#price_input').focus();
	  }
	});
	
	//show shop info
	$('a.link_show_shop').cluetip({
	  cursor:'',
	  ajaxCache: false,
	  width: 420,
	  arrows: true, 
	  dropShadow: true,
	  hoverIntent: false,
	  sticky: false,
	  mouseOutClose: false,
	  closePosition: 'title',
	  cluetipClass: 'jtip'
	});
	
	$('input.useful_action').click(function(){
		var param = $(this).attr('param');
		var url = rootPath + '/a.do?a=add_useful_count&'+param;
		var bp=$(this).parent();
		$.getJSON(url, function(j){
			var ok = j.ok;
            if (ok==1){
            	bp.css('color','green').html(successImg()+'购灵感谢您的参与！');
            } else if (ok==0){
            	bp.css('color','red').html(errImg()+'您已经投过票了！');
            } else if (ok==-2){
            	bp.css('color','red').html(errImg()+'只有登录后才能投票。请先<a href="javascript:;" onclick="showLoginDlg();">登录</a>。');
            } else{
            	bp.css('color','red').html(errImg()+'操作失败。请稍候重试。');
            }
        })
	});
	
	//compare box
	$('[name="modelCheck"]').click( function(e) {
		if (this.checked && compareCount>=5) {
			alert('最多选中5款产品进行对比。');
			return false;
		}
		
		var p1="add";
		if (!this.checked) {
			p1="remove"
		}
		
		var html = $.ajax({
		   type: "GET",
		   url: rootPath + '/a.do?a=update_cb&p1=' + p1 + '&p2=' + this.getAttribute('value'),
		   async: false
		}).responseText;
		
		fetchCompareBox();
	});
	
	fetchCompareBox();
	$('#compare_box').floatDiv({top:100,right:10});
	
	//view product list
	var lastSid;
	
	$("#ms_product_list").dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		width:600,
		open: function(event, ui) {
			$.ajax({
		        url: rootPath + "/product_dlg.html?modelID=" + modelID + "&shopID=" + lastSid, 
		        type: "GET",
		        beforeSend: function() {
		           	$('#product_list_content').hide();
		            $('#product_loading').show();
		        },
		        error: function(request) {
		            $('#product_loading').hide();
		            $('#product_list_content').show().html(errImg()+'加载时发生服务器错误。');
		        },
		        success: function(data) {
		        	$('#product_loading').hide();
		        	$('#product_list_content').show().html(data);
		        }
		    });
		},		
		close: function() {
			$('embed').css('visibility','visible');
			$('object').css('visibility','visible');
			$('select').css('visibility','visible');
		}
	});
	
	$('.btn_view_detail').click( function(e) {
		lastSid=$(this).attr('sid');
		
		$('embed').css('visibility','hidden');
		$('object').css('visibility','hidden');
		$('select').css('visibility','hidden');
		
		var title=$(this).attr('title');
		$('#ms_product_list').dialog('option', 'title', title);
		$('#ms_product_list').dialog('open');
	});
});