/* $Id: compare.js 15469 2008-12-19 06:34:44Z testyang $ */
var Compare = new Object();

Compare = {
  add : function(goodsId, goodsName, type)
  {
    var count = 0;
    for (var k in this.data)
    {
      if (typeof(this.data[k]) == "function")
      continue;
      //if (this.data[k].t != type) {
        //alert(goods_type_different.replace("%s", goodsName));
        //return;
      //}
      count++;
    }
    if (this.data[goodsId]){
      alert(exist.replace("%s",goodsName));
      return;
    }else{
      this.data[goodsId] = {n:goodsName,t:type,id:goodsId,q:1,p:0.00};
	  
    }
    this.save();
    //this.init();
  },
  
  relocation : function()
  {
    if (this.compareBox.style.display != "") return;
    var diffY = Math.max(document.documentElement.scrollTop,document.body.scrollTop);

    var percent = .2*(diffY - this.lastScrollY);
    if(percent > 0)
      percent = Math.ceil(percent);
    else
      percent = Math.floor(percent);
    this.compareBox.style.top = parseInt(this.compareBox.style.top)+ percent + "px";

    this.lastScrollY = this.lastScrollY + percent;
  },
  init : function(){
    this.data = new Object();
	
    var cookieValue = document.getCookie("compareItems");
    if (cookieValue != null) {
      this.data = cookieValue.parseJSON();
    }
	
	//alert(cookieValue);
    if (!this.compareBox)
    {
      
    }
    this.compareList.innerHTML = "";
    var self = this;
    for (var key in this.data)
    {
      if(typeof(this.data[key]) == "function")
        continue;
      var li = document.createElement("LI");
      var span = document.createElement("SPAN");
      span.style.overflow = "hidden";
      span.style.width = "100px";
      span.style.height = "20px";
      span.style.display = "block";
      span.innerHTML = this.data[key].n;
      li.appendChild(span);
      li.style.listStyle = "none";
      var delBtn = document.createElement("IMG");
      delBtn.src = "images/drop.gif";
      delBtn.className = key;
      delBtn.onclick = function(){
        document.getElementById("compareList").removeChild(this.parentNode);
        delete self.data[this.className];
        self.save();
        //self.init();
      }
      li.insertBefore(delBtn,li.childNodes[0]);
      this.compareList.appendChild(li);
    }
    if (this.compareList.childNodes.length > 0)
    {
      this.compareBox.style.display = "";
      this.timer = window.setInterval(this.relocation.bind(this), 50);
    }
    else
    {
      this.compareBox.style.display = "";
      window.clearInterval(this.timer);
      this.timer = 0;
    }
  },
  save : function()
  {
    var date = new Date();
    date.setTime(date.getTime() + 99999999);
    document.setCookie("compareItems", this.data.toJSONString());
  },
  lastScrollY : 0
}

///* ÐÞ¸´IE6ÒÔÏÂ°æ±¾PNGÍ¼Æ¬Alpha */
//function fixpng()
//{
//  var arVersion = navigator.appVersion.split("MSIE")
//  var version = parseFloat(arVersion[1])
//
//  if ((version >= 5.5) && (document.body.filters))
//  {
//     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='scale');\"></span>"
//           img.outerHTML = strNewHTML
//           i = i-1
//        }
//     }
//  }
//}
if ( ! Object.prototype.toJSONString) {
    Array.prototype.toJSONString = function () {
        var a = ['['], // The array holding the text fragments.
            b,         // A boolean indicating that a comma is required.
            i,         // Loop counter.
            l = this.length,
            v;         // The value to be stringified.

        function p(s) {

            // p accumulates text fragments in an array. It inserts a comma before all
            // except the first fragment.

            if (b) {
              a.push(',');
            }
            a.push(s);
            b = true;
        }

        // For each value in this array...

        for (i = 0; i < l; i ++) {
            v = this[i];
            switch (typeof v) {

            // Values without a JSON representation are ignored.

            case 'undefined':
            case 'function':
            case 'unknown':
                break;

            // Serialize a JavaScript object value. Ignore objects thats lack the
            // toJSONString method. Due to a specification error in ECMAScript,
            // typeof null is 'object', so watch out for that case.

            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;

            // Otherwise, serialize the value.

            default:
                p(v.toJSONString());
            }
        }

        // Join all of the fragments together and return.

        a.push(']');
        return a.join('');
    };

    Boolean.prototype.toJSONString = function () {
        return String(this);
    };

    Date.prototype.toJSONString = function () {

        // Ultimately, this method will be equivalent to the date.toISOString method.

        function f(n) {

            // Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };

    Number.prototype.toJSONString = function () {

        // JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : "null";
    };

    Object.prototype.toJSONString = function () {
        var a = ['{'],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            k,          // The current key.
            v;          // The current value.

        function p(s) {

            // p accumulates text fragment pairs in an array. It inserts a comma before all
            // except the first fragment pair.

            if (b) {
                a.push(',');
            }
            a.push(k.toJSONString(), ':', s);
            b = true;
        }

        // Iterate through all of the keys in the object, ignoring the proto chain.

        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {

                // Values without a JSON representation are ignored.

                case 'undefined':
                case 'function':
                case 'unknown':
                    break;

                // Serialize a JavaScript object value. Ignore objects that lack the
                // toJSONString method. Due to a specification error in ECMAScript,
                // typeof null is 'object', so watch out for that case.

                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;
                default:
                    p(v.toJSONString());
                }
            }
        }

          // Join all of the fragments together and return.

        a.push('}');
        return a.join('');
    };

    (function (s) {

        // Augment String.prototype. We do this in an immediate anonymous function to
        // avoid defining global variables.

        // m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        s.parseJSON = function (filter) {

            // Parsing happens in three stages. In the first stage, we run the text against
            // a regular expression which looks for non-JSON characters. We are especially
            // concerned with '()' and 'new' because they can cause invocation, and '='
            // because it can cause mutation. But just to be safe, we will reject all
            // unexpected characters.

            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this)) {

                    // In the second stage we use the eval function to compile the text into a
                    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                    // in JavaScript: it can begin a block or an object literal. We wrap the text
                    // in parens to eliminate the ambiguity.

                    var j = eval('(' + this + ')');

                    // In the optional third stage, we recursively walk the new structure, passing
                    // each name/value pair to a filter function for possible transformation.

                    if (typeof filter === 'function') {

                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) {
                                        v[i] = walk(i, v[i]);
                                    }
                                }
                            }
                            return filter(k, v);
                        }

                        j = walk('', j);
                    }
                    return j;
                }
            } catch (e) {

            // Fall through if the regexp test fails.

            }
            throw new SyntaxError("parseJSON");
        };

        s.toJSONString = function () {

          // If the string contains no control characters, no quote characters, and no
          // backslash characters, then we can simply slap some quotes around it.
          // Otherwise we must also replace the offending characters with safe
          // sequences.

          // add by weberliu @ 2007-4-2
          var _self = this.replace("&", "%26");

          if (/["\\\x00-\x1f]/.test(this)) {
              return '"' + _self.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                  var c = m[b];
                  if (c) {
                      return c;
                  }
                  c = b.charCodeAt();
                  return '\\u00' +
                      Math.floor(c / 16).toString(16) +
                      (c % 16).toString(16);
              }) + '"';
          }
          return '"' + _self + '"';
        };
    })(String.prototype);
}



function compare_List(Divcompare)
{
	
	var compare_="<table width=\"96%\" cellspacing=\"1\" cellpadding=\"3\" bgcolor=\"#FFFFFF\" style=\"margin-top:8px;\" align=\"center\">";
	
	compare_=compare_+"<tr><td width=\"20%\" align=\"center\" bgcolor=\"#CCCCCC\" style=\"color:#FFF;\">Name</td><td width='20%' align='center' bgcolor='#CCCCCC' style='color:#FFF;'>Image</td><td width='15%' align='center' bgcolor='#CCCCCC' style='color:#FFF;'>Quantity</td><td width='15%' align='center' bgcolor='#CCCCCC' style='color:#FFF;'>Prices</td><td width='15%' align='center' bgcolor='#CCCCCC' style='color:#FFF;'>Total</td><td width='15%' align='center' bgcolor='#CCCCCC' style='color:#FFF;'>Control</td> </tr>";
	this.data = new Object();
	var cookieValue = document.getCookie("compareItems");
	if (cookieValue != null) {
	this.data = cookieValue.parseJSON();
	var s=1;
	for (var k in this.data){
		if(String(this.data[k].n)!="undefined"){
			//alert(this.data[k].n);
			s++;
			compare_=compare_+"<tr><td align='center' bgcolor='#f2f2f2'><a href='http://www.jintion.com/ProductsView.Asp?id="+this.data[k].id+"' target='_blank'>"+this.data[k].n+"</a><input name='pName' type='hidden' value='"+this.data[k].n+"'/></td><td align='center' bgcolor='#f2f2f2'><a href='http://www.jintion.com/ProductsView.Asp?id="+this.data[k].id+"' target='_blank'><img src='"+this.data[k].t+"' width='50' border=0></a><input name='p_image' type='hidden' value='"+this.data[k].t+"'/></td><td align='center' bgcolor='#f2f2f2'><input name='Quantity' type='text' id='Quantity_"+s+"' value='"+this.data[k].q+"' size='5' style='text-align:center' onBlur='Calculate("+s+","+this.data[k].id+",0)'></td><td align='center' bgcolor='#f2f2f2'>$ <input name='Prices'style='text-align:center' type='text' id='Prices_"+s+"' value='"+changeTwoDecimal_f(this.data[k].p)+"' size='10' onBlur='Calculate("+s+","+this.data[k].id+",1)'></td><td align='center' bgcolor='#f2f2f2'><span id=st_"+s+">$ "+changeTwoDecimal_f(this.data[k].p*this.data[k].q)+"</span><input name='sml_price' type='hidden' value='"+changeTwoDecimal_f(this.data[k].p*this.data[k].q)+"'/></td><td align='center' bgcolor='#f2f2f2'><a href='javascript:Goto();' onclick='deleteCurrentRow(this,"+this.data[k].id+")'>Del</a><input name='pID' type='hidden' value='"+this.data[k].id+"'/></td></tr>"
		}
	}
	 }
	 compare_=compare_+"<tr><td colspan='6' align='right' bgcolor='#f2f2f2' style='color:#F00; font-family:Verdana, Geneva, sans-serif'>Total£º$<span id=totalMon> 0.00</span><input id='txtTotal' name='txtTotal' type='hidden' value=''/></td></tr>"
	compare_=compare_+"</table>";
	$(Divcompare).innerHTML=compare_;
	totalfun();
}

function Calculate(n,myid,ss)
{
	var data = new Object();
	var cookieValue = document.getCookie("compareItems");
	if (cookieValue != null) {
		data = cookieValue.parseJSON();
		if(ss==1){
			data[myid].p=$("Prices_"+n).value;
		}else{
			data[myid].q=$("Quantity_"+n).value;
		}
		document.setCookie("compareItems", data.toJSONString());
	}
	
	$("st_"+n).innerHTML=changeTwoDecimal_f(parseFloat(($("Quantity_"+n).value))*parseFloat(($("Prices_"+n).value)));
	totalfun();
}

function totalfun(){
		var tal=0.00;
	this.data = new Object();
	var cookieValue = document.getCookie("compareItems");
	if (cookieValue != null) {
	this.data = cookieValue.parseJSON();
	var s=1;
	for (var k in this.data){
		if(String(this.data[k].n)!="undefined"){
			s++;
			tal+= parseFloat(Number(this.data[k].q)) * changeTwoDecimal_f(parseFloat(this.data[k].p));
		}
	  }
	}
	$("totalMon").innerHTML=changeTwoDecimal_f(tal);
	$("txtTotal").value=changeTwoDecimal_f(tal);
}

function changeTwoDecimal_f(x)
{
var f_x = parseFloat(x);
if (isNaN(f_x))
{
alert('function:changeTwoDecimal->parameter error');
return false;
}
var f_x = Math.round(x*100)/100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0)
{
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 2)
{
s_x += '0';
}
return s_x;
}

function Goto(){}    
function deleteCurrentRow(obj,myid2){
if(confirm("To confirm the deletion?")){
	var tr=obj.parentNode.parentNode;      
	var tbody=tr.parentNode;      
	tbody.removeChild(tr);
	
	var data = new Object();
	var data2=new Object();
	var cookieValue = document.getCookie("compareItems");
	if (cookieValue != null) {
		data = cookieValue.parseJSON();
		for (var k in data){
			if(Number(k)!=Number(myid2)){
				data2[k]=data[k];
			}
		}
		document.setCookie("compareItems", data2.toJSONString());
		totalfun();
	}
}
else{}
   
} 
