/* $Id : common.js 4865 2007-01-31 14:04:10Z paulgao $ */

/* *
 * 添加商品到购物车
 */
function addToCart(goodsId)
{
  var goods        = new Object();
  var spec_arr     = new Array();
  var fittings_arr = new Array();
  var number       = 1;
  var formBuy      = document.forms['ECS_FORMBUY'];

  // 检查是否有商品规格
  if (formBuy)
  {
    j = 0;
    for (i = 0; i < formBuy.elements.length; i ++ )
    {
      var prefix = formBuy.elements[i].name.substr(0, 5);

      if (prefix == 'spec_' && (
        (formBuy.elements[i].type == 'radio' && formBuy.elements[i].checked) ||
        formBuy.elements[i].tagName == 'SELECT'))
      {
        spec_arr[j] = formBuy.elements[i].value;
        j ++ ;
      }
    }

    if (formBuy.elements['number'])
    {
      number = formBuy.elements['number'].value;
    }
  }

  // 检查是否有配件
  var formFittings = document.forms['ECS_FORMFITTINGS'];

  if (formFittings)
  {
    var fittings = formFittings.elements['fittings'];

    if (fittings != undefined)
    {
      if (fittings.length != undefined)
      {
        for (i = 0; i < fittings.length; i ++ )
        {
          if (fittings[i].checked)
          {
            fittings_arr[i] = fittings[i].value;
          }
          else
          {
            fittings_arr[i] = "0";
          }
        }
      }
      else
      {
        if (fittings.checked) fittings_arr[0] = fittings.value;
      }
    }
  }

  goods.spec     = spec_arr;
  goods.fittings = fittings_arr;
  goods.goods_id = goodsId;
  goods.number   = number;

  Ajax.call(WWW_DOMAIN_COM + '/checkout.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse, 'POST', 'JSON');
}



function addToCart_sm(goodsId)
{
  var goods        = new Object();
  var spec_arr     = new Array();
  var fittings_arr = new Array();
  var number       = 1;
  var formBuy      = document.forms['ECS_FORMBUY'];

  // 检查是否有商品规格
  if (formBuy)
  {
    j = 0;
    for (i = 0; i < formBuy.elements.length; i ++ )
    {
      var prefix = formBuy.elements[i].name.substr(0, 5);

      if (prefix == 'spec_' && (
        (formBuy.elements[i].type == 'radio' && formBuy.elements[i].checked) ||
        formBuy.elements[i].tagName == 'SELECT'))
      {
        spec_arr[j] = formBuy.elements[i].value;
        j ++ ;
      }
    }

    if (formBuy.elements['number'])
    {
      number = formBuy.elements['number'].value;
    }
  }

  // 检查是否有配件
  var formFittings = document.forms['ECS_FORMFITTINGS'];

  if (formFittings)
  {
    var fittings = formFittings.elements['fittings'];

    if (fittings != undefined)
    {
      if (fittings.length != undefined)
      {
        for (i = 0; i < fittings.length; i ++ )
        {
          if (fittings[i].checked)
          {
            fittings_arr[i] = fittings[i].value;
          }
          else
          {
            fittings_arr[i] = "0";
          }
        }
      }
      else
      {
        if (fittings.checked) fittings_arr[0] = fittings.value;
      }
    }
  }

  goods.spec     = spec_arr;
  goods.fittings = fittings_arr;
  goods.goods_id = goodsId;
  goods.number   = number;

  Ajax.call(WWW_DOMAIN_COM + '/checkout.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse_sm, 'POST', 'JSON');
}
/* *
 * 处理添加商品到购物车的反馈信息
 */
function addToCartResponse(result)
{
  if (result.error > 0)
  {
    // 如果需要缺货登记，跳转
    if (result.error == 2)
    {
      if (confirm(result.message))
      {
        location.href = WWW_DOMAIN_COM + '/user.php?act=add_booking&id=' + result.goods_id;
      }
    }
    else
    {
      alert(result.message);
    }
  }
  else
  {
    var cartInfo = document.getElementById('ECS_CARTINFO');

    if (cartInfo)
    {
      cartInfo.innerHTML = result.content;
    }

//    if (!confirm(result.message))
//    {
      location.href = WWW_DOMAIN_COM + '/checkout.php';
//    }
  }
}


function addToCartResponse_sm(result)
{
if (result.error > 0)
  {
    // 如果需要缺货登记，跳转
    if (result.error == 2)
    {
      if (confirm(result.message))
      {
        location.href = WWW_DOMAIN_COM + '/user.php?act=add_booking&id=' + result.goods_id;
      }
    }
    else
    {
      alert(result.message);
    }
  }
  else
  {
    var cartInfo = document.getElementById('ECS_CARTINFO');

    if (cartInfo)
    {
      cartInfo.innerHTML = result.content;
    }

//    if (!confirm(result.message))
//    {
      location.href = WWW_DOMAIN_COM + '/checkout.php';
//    }
  }
}
/* *
 * 添加商品到收藏夹
 */
function collect(goodsId)
{
  Ajax.call(WWW_DOMAIN_COM + '/user.php?act=collect', 'id=' + goodsId, collectResponse, 'GET', 'JSON');
}


function collect_sm(goodsId)
{
  Ajax.call(WWW_DOMAIN_COM + '/user.php?act=collect', 'id=' + goodsId, collectResponse, 'GET', 'JSON');
}

/* *
 * 处理收藏商品的反馈信息
 */
function collectResponse(result)
{
  alert(result.message);
}

/* *
 * 处理会员登录的反馈信息
 */
function signInResponse(result)
{
  toggleLoader(false);

  var done    = result.substr(0, 1);
  var content = result.substr(2);

  if (done == 1)
  {
    document.getElementById('member-zone').innerHTML = content;
  }
  else
  {
    alert(content);
  }
}

/* *
 * 评论的翻页函数
 */
function gotoPage(page, id, type)
{
  Ajax.call(WWW_DOMAIN_COM + '/comment.php?act=gotopage', 'page=' + page + '&id=' + id + '&type=' + type, gotoPageResponse, 'GET', 'JSON');
}


function gotoPage_sm(page, id, type)
{
  Ajax.call(WWW_DOMAIN_COM + '/comment.php?act=gotopage', 'page=' + page + '&id=' + id + '&type=' + type, gotoPageResponse, 'GET', 'JSON');
}

function gotoPageResponse(result)
{
  document.getElementById("ECS_COMMENT").innerHTML = result.content;
}

/* *
 * 取得格式化后的价格
 * @param : float price
 */
function getFormatedPrice(price)
{
  if (currencyFormat.indexOf("%s") > - 1)
  {
    return currencyFormat.replace('%s', advFormatNumber(price, 2));
  }
  else if (currencyFormat.indexOf("%d") > - 1)
  {
    return currencyFormat.replace('%d', advFormatNumber(price, 0));
  }
  else
  {
    return price;
  }
}

/* *
 * 夺宝奇兵会员出价
 */

function bid(step)
{
  var price = '';
  var msg   = '';
  if (step != - 1)
  {
    var frm = document.forms['formBid'];
    price   = frm.elements['price'].value;
    if (price.length == 0)
    {
      msg += price_not_null + '\n';
    }
    else
    {
      var reg = /^[\.0-9]+/;
      if ( ! reg.test(price))
      {
        msg += price_not_number + '\n';
      }
    }
  }
  else
  {
    price = step;
  }

  if (msg.length > 0)
  {
    alert(msg);
    return;
  }

  Ajax.call(WWW_DOMAIN_COM + '/snatch.php?act=bid', 'price=' + price, bidResponse, 'POST', 'JSON')
}

/* *
 * 夺宝奇兵会员出价反馈
 */

function bidResponse(result)
{
  if (result.error == 0)
  {
    document.getElementById('ECS_SNATCH').innerHTML = result.content;
    if (document.forms['formBid'])
    {
      document.forms['formBid'].elements['price'].focus();
    }
    newPrice(); //刷新价格列表
  }
  else
  {
    alert(result.content);
  }
}

/* *
 * 夺宝奇兵最新出价
 */

function newPrice()
{
  Ajax.call(WWW_DOMAIN_COM + '/snatch.php?act=new_price_list', '', newPriceResponse, 'GET', 'TEXT');
}

/* *
 * 夺宝奇兵最新出价反馈
 */

function newPriceResponse(result)
{
  document.getElementById('ECS_PRICE_LIST').innerHTML = result;
}

/* *
 *  返回属性列表
 */
function getAttr(cat_id)
{
  var tbodies = document.getElementsByTagName('tbody');
  for (i = 0; i < tbodies.length; i ++ )
  {
    if (tbodies[i].id.substr(0, 10) == 'goods_type')tbodies[i].style.display = 'none';
  }

  var type_body = 'goods_type_' + cat_id;
  try
  {
    document.getElementById(type_body).style.display = '';
  }
  catch (e)
  {
  }
}

/* *
 * 截取小数位数
 */
function advFormatNumber(value, num) // 四舍五入
{
  var a_str = formatNumber(value, num);
  var a_int = parseFloat(a_str);
  if (value.toString().length > a_str.length)
  {
    var b_str = value.toString().substring(a_str.length, a_str.length + 1);
    var b_int = parseFloat(b_str);
    if (b_int < 5)
    {
      return a_str;
    }
    else
    {
      var bonus_str, bonus_int;
      if (num == 0)
      {
        bonus_int = 1;
      }
      else
      {
        bonus_str = "0."
        for (var i = 1; i < num; i ++ )
        bonus_str += "0";
        bonus_str += "1";
        bonus_int = parseFloat(bonus_str);
      }
      a_str = formatNumber(a_int + bonus_int, num)
    }
  }
  return a_str;
}

function formatNumber(value, num) // 直接去尾
{
  var a, b, c, i;
  a = value.toString();
  b = a.indexOf('.');
  c = a.length;
  if (num == 0)
  {
    if (b != - 1)
    {
      a = a.substring(0, b);
    }
  }
  else
  {
    if (b == - 1)
    {
      a = a + ".";
      for (i = 1; i <= num; i ++ )
      {
        a = a + "0";
      }
    }
    else
    {
      a = a.substring(0, b + num + 1);
      for (i = c; i <= b + num; i ++ )
      {
        a = a + "0";
      }
    }
  }
  return a;
}

/* *
 * 根据当前shiping_id设置当前配送的的保价费用，如果保价费用为0，则隐藏保价费用
 *
 * return       void
 */
function set_insure_status()
{
  // 取得保价费用，取不到默认为0
  var shippingId = getRadioValue('shipping');
  var insure_fee = 0;
  if (shippingId > 0)
  {
    if (document.forms['theForm'].elements['insure_' + shippingId])
    {
      insure_fee = document.forms['theForm'].elements['insure_' + shippingId].value;
    }
    // 每次取消保价选择
    if (document.forms['theForm'].elements['need_insure'])
    {
      document.forms['theForm'].elements['need_insure'].checked = false;
    }

    // 设置配送保价，为0隐藏
    if (document.getElementById("ecs_insure_cell"))
    {
      if (insure_fee > 0)
      {
        document.getElementById("ecs_insure_cell").style.display = '';
        setValue(document.getElementById("ecs_insure_fee_cell"), getFormatedPrice(insure_fee));
      }
      else
      {
        document.getElementById("ecs_insure_cell").style.display = "none";
        setValue(document.getElementById("ecs_insure_fee_cell"), '');
      }
    }
  }
}

/* *
 * 当支付方式改变时出发该事件
 * @param       pay_id      支付方式的id
 * return       void
 */
function changePayment(pay_id)
{
  // 计算订单费用
  calculateOrderFee();
}

function getCoordinate(obj)
{
  var pos =
  {
    "x" : 0, "y" : 0
  }

  pos.x = document.body.offsetLeft;
  pos.y = document.body.offsetTop;

  do
  {
    pos.x += obj.offsetLeft;
    pos.y += obj.offsetTop;

    obj = obj.offsetParent;
  }
  while (obj.tagName.toUpperCase() != 'BODY')

  return pos;
}

function showCatalog(obj)
{
  var pos = getCoordinate(obj);
  var div = document.getElementById('ECS_CATALOG');

  if (div && div.style.display != 'block')
  {
    div.style.display = 'block';
    div.style.left = pos.x + "px";
    div.style.top = (pos.y + obj.offsetHeight - 1) + "px";
  }
}

function hideCatalog(obj)
{
  var div = document.getElementById('ECS_CATALOG');

  if (div && div.style.display != 'none') div.style.display = "none";
}


// JavaScript Document

	var title = window.document.title;
	var description = "";

	function popBookmarkLinks(whatToDo) {
		if (whatToDo == "show") {
			document.getElementById('bookmarkContainer').style.visibility = 'visible';
		} else {
			document.getElementById('bookmarkContainer').style.visibility = 'hidden';
		}
	}
	
	function addbookmark()
	{
		bookmarkurl="http://www.tigerdirect.ca/indexca.asp?SRCCODE=CANBOOKMARK"
		bookmarktitle="TigerDirect Canada - Your Best Source For All Your PC Needs."
		if (document.all)
		window.external.AddFavorite(bookmarkurl,bookmarktitle)
	}
	
	<!-- Bookmark -->

	function bookmarksite(title,url){
		if (window.sidebar) {
			window.sidebar.addPanel(title, url, "");

		} else if(window.opera && window.print) {
			var elem = document.createElement('a');
			elem.setAttribute('href',url);
			elem.setAttribute('title',title);
			elem.setAttribute('rel','sidebar');
			elem.click();

		} else if(document.all) {
			window.external.AddFavorite(url, title);
		}
	}

	function loadPage(site, pageTitle, pageDescription) {
		var rawURL = window.location.href;
		rawURL = rawURL.replace("#", "");

		if (rawURL.indexOf("SRCCODE=") > 0) {
			rawURL = rawURL.replace("SRCCODE=", "SRCCODE=WEBDIGG&OLDSRC=");
		} else if (rawURL.indexOf("?") > 0) {
			rawURL = rawURL + "&SRCCODE=WEBDIGG";
		} else {
			rawURL = rawURL + "?SRCCODE=WEBDIGG";
		}

		var currentURL = encodeURIComponent(rawURL);
		var title = encodeURIComponent(pageTitle);

		var bodytext = encodeURIComponent(pageDescription);

		var newURL;
		var go = true;

		switch (site) {
			case "del.icio.us":
				newURL = "http://del.icio.us/post?v=4"
				+ ";url=" + currentURL
				+ ";title=" + title;
			break;
			case "digg":
				newURL = "http://digg.com/submit?phase=2&"

				+ "url=" + currentURL

				+ "&title=" + title

				+ "&bodytext=" + bodytext

				+ "&topic=tech_deals";

			break;
			case "reddit":
				newURL = "http://reddit.com/submit?"
				+ "url=" + currentURL
				+ "&title=" + title;
			break;
			case "furl":
				newURL = "http://www.furl.net/savedialog.jsp?"
				+ "t=" + title
				+ "&u=" + currentURL;
			break;
			case "rawsugar":
				newURL = "http://www.rawsugar.com/home/extensiontagit/?turl=" + currentURL
				+ "&tttl=" + title;
			break;
			case "stumbleupon":
				newURL= "http://www.stumbleupon.com/submit?url=" + currentURL
				+ "&title=" + title;
			break;
			case "blogmarks":
				
			break;
			case "facebook":
				newURL = "http://www.facebook.com/share.php?src=bm&v=4" 
				+ "&u=" + currentURL
				+ "&t=" + title;
			break;
			case "technorati":
				newURL = "http://technorati.com/faves?sub=favthis&add=" + currentURL;
			break;
			case "spurl":
				newURL = "http://www.spurl.net/spurl.php?v=3"
				+ "&title=" + title
				+ "&url=" + currentURL;
			break;
			case "simpy":
				newURL= "http://www.simpy.com/simpy/LinkAdd.do?title=" + title
				+"&href=" + currentURL;
			break;
			case "ask":
				
			break;
			case "google":
				newURL = "http://www.google.com/bookmarks/mark?op=edit&output=popup"
				+ "&bkmk=" + currentURL
				+ "&title=" + title;
			break;
			case "netscape":
				newURL = "http://www.netscape.com/submit/?U=" + currentURL
				+ "&T=" + title + "&C=" + bodytext;
			break;
			case "fark":
				
			break;
			case "slashdot":
				newURL = "http://slashdot.org/bookmark.pl?url=" + rawURL + "&title=" + title;
			break;
			case "backflip":
				newURL= "http://www.backflip.com/add_page_pop.ihtml?" 
				+ "title=" + title
				+ "&url=" + currentURL;
			break;
			case "wink":
				
			break;
			case "bluedot":
				newURL = "http://bluedot.us/Authoring.aspx?"
				+ "u=" + currentURL
				+ "&t=" + title;
			break;
			case "browser":
				bookmarksite(pageTitle, rawURL);
				go = false;
			break;
		}

		if (go == true) {
			window.open(newURL, "bookmarkWindow");
		}
	}
	
	
	
