//global object contain some global var
var globalObj = {
	cookieOpt : {expires: 30, path: '/', domain: 'smarter.com'},
	prodDetailUrl :  '/async_prod.php',
	allAttrUrl : '/async_attr.php',
	itemLimit : 30
};
$(document).ready(function (){
var cookieOpt = globalObj.cookieOpt || {expires: 30, path: '/', domain: 'smarter.com'};
var rv = $.cookie('RecentlyViewed');//'33-123213-11/01/08|22-212324-12/02/09'
var ml = $.cookie('MyList')||'';
var prodListFormat = /(\d+-\d+-\d+x\d+x\d+\*?)+/;
var prodDetailUrl = globalObj.prodDetailUrl || '/async_prod.php';
var allAttrUrl = globalObj.allAttrUrl || '/async_attr.php';//@todo replace with true data
var noImage = fileServer+"images/default/prod_noimage_s.jpg";
var msgDivMinHeight = "80";//simple will change the css later
var tmp = ml.split('*');
var pages = 1;
var pp = 6;
var pn = 1;
var itemLimit = globalObj.itemLimit || 30;
var lin = tmp.length;
if (lin>pp) pages = Math.ceil(lin/pp);

var setPageBtnStatus = function(pn,pages){
    if(pages<2) return $('div.pageselect').hide();
    else $('div.pageselect').show();
    
    $('div.pageselect > p').html('Page '+pn+' of '+pages);
    
    var prev = $('div.pageselect > a.prev > img');
    var prev_normal = fileServer+'images/v5/prev_but.gif';
    var prev_none = fileServer+'images/v5/none_prev_but.gif';
    var next = $('div.pageselect > a.next > img');
    var next_normal = fileServer+'images/v5/next_but.gif';
    var next_none = fileServer+'images/v5/none_next_but.gif';
    
    if(pn<=1) prev.attr('src',prev_none);
    else prev.attr('src',prev_normal);
    if(pn==pages) next.attr('src',next_none);
    else next.attr('src',next_normal);
};

//global function,also server for prodlist.js
 loadAjaxData = function(dt){ // function load data by ajax
    //working with recently viewed block
    if (dt=='all'||dt=='rv'){
	    var rv = $.cookie('RecentlyViewed')||'';
		if ($('div.recentlyviewed').attr('data')!=rv && prodListFormat.test(rv)) {
			var rvHtml = "<ul>";
		    jQuery.post(prodDetailUrl, {'dt':'base', 'data':rv}, function(data, textStatus){
		        data = data.prods;
		        for(i in data){
		            var from = 'from';
		            var priceStr = '$'+data[i].min_price;;
		            if (data[i].min_price == data[i].max_price) from = 'for';
		            if (data[i].img=="") data[i].img = noImage;
		            if (data[i].min_price <= 0) {/*no price or price <= 0*/
		                priceStr = 'See It';
		                from = '';
		            }
		            rvHtml += '<li><a href="'+data[i].home_url+'" target="_blank"><img src="'+data[i].img
		                      +'"/></a>'+from+' <a href="'+data[i].home_url+'" target="_blank">'
		                      +priceStr+'</a></li>';
		        }
		        rvHtml += '</ul>';
		        $('div.recentlyviewed > ul').remove();
		        $('div.recentlyviewed').attr('data',rv).prepend(rvHtml);
		        $('div.recentlyviewed > div.clearhistory').show();
		    }, 'json');	//use json to save the triffic
		} else if(rv=='') {
		  $('div.recentlyviewed > ul').remove();
		  $('div.recentlyviewed > div.clearhistory').hide();
		  $('div.recentlyviewed').prepend('<ul><li class="msg">Your Recently Viewed list is empty!</li></ul>');
		}
	}
	// working with mylist
	if (dt=='all'||dt=='ml'){
		var ml = $.cookie('MyList')||'';
		if (prodListFormat.test(ml)) {
		    //setPageBtnStatus(1,pages);
		    var mlHtml = "";
		    //hide products on current page which has been added
		    var items = ml.split('*');
		    for (x in items){
		      var temp = items[x].split('-');
		      $('a.savetowishlist[name="'+temp[0]+'-'+temp[1]+'"]').text('Saved!').addClass('saved');
		    }
		    //load data by AJAX
		    jQuery.post(prodDetailUrl, {'dt':'base', 'data':ml}, function(data, textStatus){
		        var data = data.prods;
		        var lc = ml.split('*').reverse();//localCookie
		        var k = 0;
		        for(i in data){
		            if ((i-0+k)%pp==0) mlHtml += "<ul class='disn'>";
		            if (data[i].chid<10) data[i].chid = '0'+data[i].chid;
		            if (data[i].img=="") data[i].img = noImage;
		            var priceStr = '$'+data[i].min_price+' - $'+data[i].max_price;
		            var nameStr = data[i].chid+'-'+data[i].pid+'-'+data[i].date;
		            if (data[i].min_price == data[i].max_price) priceStr = '$'+data[i].min_price;
		            if (data[i].min_price <=0 ) priceStr = 'See It';
		            if(lc[i] != nameStr){
		                k++;
		                var tmpArr = lc[i].split('-');
		                var img = 'http://images.smarter.com/90x90x15/'+tmpArr[0]+'/'+tmpArr[1].substr(-2)+'/'+tmpArr[1]+'.jpg';
		                mlHtml += '<li><a href="#"><img src="'+img+'"></a>'
		                       + '<a href="#">&nbsp;</a><p>Not on sell<br /></p>'
		                       +'<span><a href="#" name="'+lc[i]+'">Delete</a>Saved '+tmpArr[2].replace(/x/g, '/')+'</span></li>'
                        lc.splice(i,1);
		            }
			        mlHtml += '<li><a href="'+data[i].home_url+'" target="_blank"><img src="'+data[i].img
			                  +'"/></a><a href="'+data[i].home_url+'" target="_blank">'
			                  +priceStr+'</a>'+'<p> '+data[i].name+' </p>'
			                  +'<span><a href="#" target="_blank" name="'+nameStr
			                  +'">Delete</a>Saved '+data[i].date.replace(/x/g, '/')+'</span>'
			                  +'</li>';
			        if((i-0+k)%pp==(pp-1)) mlHtml += "</ul>\n";
		        }
		        // reset pages and button status
		        pages = Math.ceil(ml.split('*').length/pp);
		        pn = 1;
		        setPageBtnStatus(1,pages);
		        $('div.overmylist').fadeOut('fast');
		        if(lin%pp!=0) mlHtml += "</ul>\n";//for more than one pages
		        $('div.mylist > ul').remove();//clear old results
		        $('div.mylist').prepend(mlHtml).children('ul:first').show();//show the first page
		        //when delete item link clicked
				$('div.mylist > ul > li > span > a').click(function(){
				    var data = $(this).attr('name');
				    delItemFromCookie('MyList',data);
				    var temp = data.split('-');
				    //restore the save link if its avaliable on current page
				    $('a.savetowishlist[name="'+temp[0]+'-'+temp[1]+'"]').text('Save to Wish List').removeClass('saved');
                    $(this).parent().parent().hide();
				    if($.cookie('MyList') && $.cookie('MyList').length>0){
					    var h = $('div.mylist').outerHeight();
					    $('div.overmylist').height(h).css({'opacity':'0.8', 'margin-top':'-'+h+'px'}).show();
                    }
				    loadAjaxData('ml');//reload data after delete one item
				    return false;
				});
		    }, 'json');
		} else if(ml=='') {
		    $('div.overmylist').fadeOut('fast');
            $('div.mylist > ul').remove();
            $('div.mylist').prepend('<ul><li class="msg">Your Wish List is empty!</li></ul>');
            setPageBtnStatus(0,0);
		}
	}
};

//delete one item from cookie
var delItemFromCookie = function(ckName,data){
    var ml = $.cookie(ckName);
    var cd = data;
    if(ml.indexOf(cd)!=-1){
        pos = ml.indexOf(cd);
        len = cd.length;
        var next = ml.substr(pos+len,1);
        if(next!=''){
            ml = ml.substr(0,pos)+ml.substr(pos+len+1);
        } else {
            if(ml == cd) ml = "";
            else ml = ml.substr(0,pos-1);
        }
        $.cookie(ckName, ml, cookieOpt);
        return true;
    }
    return false;
}

//pageup/down on mylist block
$('div.pageselect > a').click(function(){
    var isNext = $(this).blur().hasClass('next');
    if(isNext){
        if(pn<pages) pn++;
    } else {//isPrev
        if(pn>1) pn--;
    }
    setPageBtnStatus(pn,pages);
    $('div.mylist > ul').hide().eq(pn-1).fadeIn('fast');
    return false;
});

//clear recently viewed list with an confirm
$('div.clearhistory > a').click(function(){
    if(confirm('Are you sure you want to clear your history?')) {
        $.cookie('RecentlyViewed','',cookieOpt);
        $('div.recentlyviewed > ul').remove();
        $('div.recentlyviewed > div.clearhistory').hide();
    }
    return false;
});

$('a.savetowishlist').click(function(){//need check douple
    var timeout = 5000;
    var ml = $.cookie('MyList')||'';
    var data = $(this).attr('name');
    var t1 = $(this).parents('td.t2').siblings('td.t1');
    if (ml==null) ml = '';
    // stop when already in mylist
    if (ml.indexOf(data)!=-1)  {
        //var o = $('div.alreadyin').clone().prependTo(t1).fadeIn('fast').children('div').css('height',t1.parent().css('height'));
        //window.setTimeout(function(){o.find('a.close').click();},timeout);
        return false;
    }
    // overflow
    if (ml.split('*').length>=itemLimit) {
        var o = $('div.addfailbox:not(.alreadyin)').clone().prependTo(t1).fadeIn('fast').children('div').height(t1.parent().outerHeight());
        window.setTimeout(function(){o.find('a.close').click();},timeout);
        return false;
    }    
    // start pack data
    d = new Date(); 
    var s = (d.getUTCMonth() + 1) + 'x' + d.getUTCDate() + 'x' + d.getUTCFullYear();
    data += '-'+s;
    if(ml!='') data = '*'+data;
    $.cookie('MyList', ml+data, cookieOpt);
    //show overdiv
    var h = $('div.mylist').outerHeight();
    $('div.overmylist').height(h).css({'opacity':'0.8', 'margin-top':'-'+h+'px'}).show();
    // reload data by AJAX
    loadAjaxData('ml');
    // show msg
    var o = $('div.addokbox').clone().prependTo(t1).fadeIn('fast').children('div').height(t1.parent().outerHeight());
    o.find('td').css('background','#7399ac');//fix a bug about background is blank when the merchant is featured
    // hide msg after some seconds
    window.setTimeout(function(){o.find('a.close').click();},timeout);
    $(this).blur().text('Saved!').addClass('saved');//change self text
    return false;
});

loadAjaxData('all');// do load data first
window.setInterval(function(){loadAjaxData('rv');}, 2000);//reload recently viewed every 2s, no change no action

//start attributes action
$('div.pllcontent > div.sbox > div.data > ul > li:not(.over2)').mouseover(function(){
    $(this).mouseout().addClass($(this).attr('class')+'over');
}).mouseout(function(){
    $(this).removeClass('over').removeClass('moreover');
});

//attributes more action
$('div.pllcontent > div.sbox > div.data > ul > li.more > a').click(function(){
    //return false;//disable now
    var data = $(this).attr('name');
    var tmp = data.split('-');
    if(tmp[0]!='at'||isNaN(tmp[1]-0)) return false;
    var li = $(this).parent();
    var arr_ex = [],ex='';
    li.siblings('li').each(function(){ arr_ex.push($(this).attr('data'));});
    if (arr_ex.length > 0) { ex = arr_ex.join();}
    var div = li.parent().parent();
    if(div.siblings('div.moreattributes:visible').length>0) return false;//if already show out, return
    div.siblings('div.moreattributes:hidden').remove();//remove any other div exists
    var ma = $('div.moreattributes:last').clone().insertAfter(div).fadeIn('fast');
    //set close link action
    ma.find('div.wrapper a.close').click(function(){
        ma.remove();
        return false;
    });
    var indexArea = ma.find('div.letterarea');
    //fill popup title text
    var title =div.siblings('div.tit').find('h3').text();
    indexArea.parent().siblings('h4').html(title);

    // build post data    
    var para = parseUrl();
    var pdata = {ref:para.shift(), at:tmp[1], ex:ex, attr:[]};
    if(pdata.ref=='se'){pdata.kw = keyWord;}
    for(i in para){
        var tmp = para[i].split('-');
        switch(tmp[0]){
            case 'tt':
            case 'ch':
                pdata.ch = tmp[1];
            break;
            case 'cc':
            case 'ca':
                pdata.cat = tmp[1];
            break;
            case 'mf':
                if (!(title == 'Brand' && $.inArray(tmp[1], arr_ex) > -1)) {
                     pdata.brand = tmp[1];
                }
            break;
             case 'mi':
                if (!(title == 'Store' && $.inArray(tmp[1], arr_ex) > -1)) {
                     pdata.merchant = tmp[1];
                }
            break;
            case 'td':
                 if (!(title != 'Store' && title != 'Brand' && $.inArray(tmp[1], arr_ex) > -1)) {
                      pdata.attr.push(tmp[1]);
                 }
            break;
            default:
            break;
        }
    }
    if(pdata.attr.length>0) {
        pdata.attr = pdata.attr.join();
    }else{
        delete pdata.attr;
    }

    jQuery.post(allAttrUrl, pdata, function(data, textStatus){
        var vals = data.values;//attr values
        var inds = data.indexs;//attr group index
        if(!vals||vals.length==0) {//data is null
            ma.remove();//hide it and return
            return false;
        }
        var dt = data.attrtype;//td,mf,fi
        var atid = 'at_'+pdata.at+'_'+Math.ceil(Math.random()*1000);
        var ct = ma.find('div.content');
        indexArea.find('span').each(function(){
            $(this).parent().click(function(){return false;});//no action on #
            var val = $(this).text();
            if(inds[val]) {
                var a = $(this).parent();//enable some links
                a.attr('href','#'+atid+'_'+val)
                .removeClass('noresult')
                .click(function(){
                    ct.scrollTo($('a[name="'+atid+'_'+val+'"]'));//use jQuery.ScrollTo to jump
                    return false;
                });
            }
        });
        var html = "";
        var olda = li.siblings('li[data]:not(.over2):last').find('a:first');
        for(idx in vals){
            var attrs = vals[idx];
	        html += "<strong><a name='"+atid+'_'+idx+"'>"+idx+"</a></strong><ul><li><ul>";
	        var newUl = Math.ceil(attrs.length/3);
	        for(id in attrs){
	        	var pc = pdata.ref != 'vl'? (attrs[id][1]==0 ? '' : '('+attrs[id][1]+')') : '';
	            var urlName = attrs[id][3] ? 'urlName="'+attrs[id][3]+'"' : '';
	            html += '<li><a href="#" data="'+attrs[id][0]+'" '+urlName+'>'+attrs[id][2]+'</a> <em>'+pc+'</em> </li>';
	            if ((id-0)!=(attrs.length-1) && (id-0+1)%newUl==0) html += '</ul></li><li><ul>';
	        }
	        html += '</ul></li></ul>';
        }
        ct.html(html)
        .find('a[data]').click(function(){//bind link click
            if(!olda) return false;
            var href = olda.attr('href');
            var name = getUrlName(olda.attr('title'));
            var id = olda.parent().attr('data');
            if(id.indexOf('-')>=0){
                var ne = $(this).attr('data').split('-');
                var ol = id.split('-');
                //var oldName = olda.parent().attr('urlName');
                var thisHref = href.replace(getUrlName(olda.parent().attr('name')), getUrlName($(this).attr('urlName')))
                                   .replace('--tt-'+ol[0]+'--cc-'+ol[1], '--tt-'+ne[0]+'--cc-'+ne[1]);
                //var thisHref = '/'+getUrlName($(this).attr('urlName'))+'/se--qq-'+keyWord+'--pt-1--tt-'+tmp[0]+'--cc-'+tmp[1]+'.html';
            } else {
                var thisHref = href.replace(name, getUrlName($(this).text())).replace('-'+id, '-'+$(this).attr('data'));
            }
            //console.log(thisHref);
            location.href = thisHref;
            return false;
        });
        ma.fadeIn('fast');
        return;		        
    }, 'json');
    return false;
});

//stop button a tag jump action
$('a[href="#"]').click(function(){return false;});

var closeAll = function() { 
	$("div.wrap").html('');
    $("img[src*='popup_short_bg']").hide(); 
    $("img[src*='popup_high_bg']").hide(); 
    $('div.overlay').hide();
    $('div.overlayvideo').hide();
    $('div.overlayhigh').hide();        
};

//icons like coupon, rebates, blogs, video
	$('img.iconplus').each(function(i) {//show big image
		var iconplus = $(this).attr('id');
		var tr = $(this).parents('tr');
		var dy = $(this).attr('overlay');
		
		$(this).overlay({
			onBeforeLoad: function(){
				var bima = tr.find('td.t1 a:eq(1)').attr('href');
				var bimg = tr.find('td.t1 img:eq(1)').attr('src');
				bimg = bimg.replace('product_image_s', '300x300x15');
				var title = tr.find('td.t2 h3').html();
				var stores = tr.find('td.t3 li.stores').text();
				stores = (stores) ? 'at '+stores : '';
				var button = tr.find('td.t3 :button').hasClass('compareprice') ? 'compare_but.gif' : 'seeit_but.gif';
				var nofollow = button=='seeit_but.gif'?'rel="nofollow"':'';
				var price  = tr.find('td.t3 li.price').html();
				var wrap = $(dy+" div.wrap");
				var guidesterData = tr.attr('name');
				if(guidesterData!=''){//is a guidester product
					var pos = tr.attr('position');
					var ch_cat_data = tr.find('a.savetowishlist').attr('name');
	                var chid = ch_cat_data.split('-')[0]-0;
	                var prodid = ch_cat_data.split('-')[1]-0;
	                var cateid = guidesterData.split('-')[0]-0;
	                var mercount = guidesterData.split('-')[1]-0;
	                var trackingUrl = "/stats/scripts/async.php?";
	                    trackingUrl += 'bt=105&pagenum=1';
	                    trackingUrl += '&chid='+chid;
	                    trackingUrl += '&cateid='+cateid;
	                    trackingUrl += '&prodid='+prodid;
	                    trackingUrl += '&displaypos='+pos;
	                    trackingUrl += '&mercount='+mercount;
	                    trackingUrl += '&resultcount='+(tr.siblings().length+1);
	                jQuery.post(trackingUrl, null, function(data, textStatus){});
                }
				wrap.html('');
				var shtml = '';
					shtml += '<div class="plenlargewrapper"><div class="enlargecontent">';
					shtml += '<strong>&nbsp;</strong>';
					shtml += '<div class="imgbox"><a href="' + bima + '" border="0" target="_blank" '+nofollow+'><img src="' + bimg + '"></a></div>';
				    shtml += '<div class="caption"><a href="' + bima + '" target="_blank" '+nofollow+'>' + title + '</a></div>';
				    shtml += '<div class="store">'+ price + ' ' + stores +'</div>';
				    shtml += '<div class="submit"><a href="' + bima + '" target="_blank" '+nofollow+'><img src="'+ fileServer + 'images/v5/' + button + '" /></a></div>';
					shtml += '</div></div>';					
				wrap.html(shtml);	
			},
			// common configuration for each overlay
			oneInstance: false, 
			closeOnClick: true,
			close: 'div.close',
			onClose: function(){closeAll();}
		});			
	});

	$('a.video').each(function() {//show video and enable drag
		var dt = $(this).attr('className');
		var da = $(this).attr('name');
		
		$(this).overlay({
			onLoad: function(){
				var wrap = $("div.wrap"); 
				jQuery.post(prodDetailUrl, {'dt':dt, 'data':da}, function(data, textStatus){
				    if(!data[0]) return false;
					var vals = data[0].values[0]||null;
					wrap.html('');
					$f('popplayer', {src:fileServer+'jscript/flowplayer/flowplayer.commercial-3.0.3.swf', wmode:'opaque'}, {
						key: '#$6157e3f46cb330bc4aa',	
						playlist: [
							{
								url: vals['imageurl'],
								scaling: 'orig'
							},
							{
								url: vals['url'],
								autoPlay: false
							}
						],
						plugins:{
							controls:{
								url: fileServer+'jscript/flowplayer/flowplayer.controls-3.0.3.swf',
								fullscreen: false,
								time: false,
								backgroundColor: '#3C3D37',
								backgroundGradient: 'low',
								buttonColor: '#BDCD80',
								buttonOverColor: '#BDCD80',
								timeColor: '#ffffff',
								progressColor: '#9FB086',
								bufferColor: '#9FB086'
							}
						}
					});	
				}, 'json');
			},	
			closeOnClick: true,
			close: 'div.close',  
			// when overlay is closed, unload our player 
			onClose: function(){closeAll();}			
		});	
		//Handle Drag
	});
	
	$('#overlaybox')//enable drag
	    .bind('dragstart',function( event ){
                return $(event.target).is('.handle');
                })
        .bind('drag',function( event ){
	        	$( this ).css({
	                top: event.offsetY,
	                left: event.offsetX
	                });
                $('img[src*="popup_video_bg"]:visible').css({
                        top: event.offsetY,
                        left: event.offsetX
                        });
                });
	
	// setup triggers rebate
	$('a.rebate, a.coupon, a.blog, a.review').each(function(i) {
		var dt = $(this).attr('className');
		//var da = $(this).attr('name');
		var dy = $(this).attr('overlay');
		var wrap = $(dy+" div.wrap"); 
		var papa = $(this).parents('td.t2');
		var lidisn = papa.siblings('td.t3').find('li[name="popup"]');
		$(this).overlay({
			onBeforeLoad: function(){
				var shtml = lidisn.find('div[name="popup'+dt+'"]').clone().html() || '';
				wrap.html(shtml);
				//change rebate price=0 style
				 if(dt=='rebate'){
					var amount = wrap.find('li.amount');
					if($.trim(amount.text()).slice(-2)=='$0'){
						amount.html('<strong>Rebate Amount:</strong>Free Gift');
					}
				 }
			},
			onLoad:function() {
				//add copy flash after wrap dom complete
				if(dt=='coupon'){
					wrap.find('div.couponlist').each(function(i){
						var t = $(this).find(' li.code>a');
						var store_url = t .attr('href');
			    		var coupon_code = t .text();
			    		t.after(createFlash(coupon_code,i,store_url));
					});
				}
				$(dy).addClass('background'+(dy=='div.overlay'?'short':'high'));
			},
			// common configuration for each overlay
			oneInstance: false, 
			closeOnClick: true, 
			close: 'div.close',
			onClose: function(){wrap.empty();$(dy).hide(100);}			
		});			
	});


//tentoe (showcase) click action
$('a.showcase').click(function(){
    var data = $(this).attr('name').split('-');
    if(!data[0]) return false;
    var ttpid = 'TTPID-B00-1399';
    var vsr_sku = (data[0]-0)+'-'+data[1];
    var sLink = 'http://syndicate.tentoe.com/Syndicate/SynMaster?ttpid='+ ttpid +'&vsr_sku='+ vsr_sku;
                //+ '&vsr_price='+ '&vsr_stock='+ '&vsr_shopping_cart='+ '&vsr_call_back='
                //+'&ParentUrl=' + escape(window.location.href);
    window.open(sLink,'_blank', 'width=536,height=525,scrollbars=no,toolbar=no,personalbar=no,statusbar=no,directories=no,location=no,resizable=no,menubar=no,locationbar=no');
});

//left attribute events, sitch +/- images
$('div.pllcontent div.sbox > div.tit').click(function(){
    var isIe = $.browser.msie;
    var data = $(this).siblings('div.data');
    var select = fileServer+'images/v5/desc_sbox_icon_select.gif';
    var normal = fileServer+'images/v5/desc_sbox_icon_normal.gif';
    var img = $(this).children('div').children('img');
    if(img.attr('src')==select) {
        img.attr('src',normal);
        if(isIe) data.animate({height: "toggle"}, 200).find('ul').hide();
    } else {
        img.attr('src',select);
        if(isIe) data.animate({height: "toggle"}, 200, function(){data.find('ul').show();}).find('ul').hide();
    }
    if(!isIe) data.slideToggle('fast');
    return false;
});
//bind attr label link click action
$('div.pllcontent div.sbox > div.tit > div.right > a').click(function(){$(this).parent().parent().click();});

//roll up some divs without a expand class
$('div.sbox > div.hide').each(function(){
    $(this).click();
});

$('div.inputprice div.content > input.txt').click(function(){
    if($(this).val().substr(0,1)=='m') $(this).val('');
    $(this).css('font-style','normal');
	$(this).css('color','#000');//clear min,max text
    $(this).siblings('input.but').removeClass('over').addClass('over');
}).focus(function(){$(this).click();});

//do same replace work like the php script (G::getUrlName)
var getUrlName = function(s){
    return s?s.toLowerCase().replace(/(\s+$|^\s+|['"]|\(.*\))/g,'').replace(/([^a-z0-9]|-)+/g, '-'):s;
};
var parseUrl = function(){
    url = location.href.split('/');
    return url[url.length-1].split('.html')[0].split('--');
};

//isParaCutPage
var isParaCutPage = $.cookie('isParaCutPage');
if(isParaCutPage&&isParaCutPage==1){
    var obj = $('div.pronofound').find('a.close')
    .after('Sorry! We could not find any products related to your search, please see results below.').end().show();
    $.cookie('isParaCutPage', 0, cookieOpt);
    obj.find('a.close').click(function(){
        obj.hide().remove();
    });
    window.setTimeout(function(){obj.find('a.close').click();},10000);
}

//SDC page list links change
if(onlySdc=='YES'){
	$('div.pagelist a').each(function(){
	    if($(this).attr('href').indexOf('--bn-')!=-1){
	       var arr = $(this).attr('href').split('--bn-')[1].split('0');
	       $(this).attr('href', location.href.split('.html')[0]+'.html?tt=102&bn='+arr[0]+'0');
	    }
	});
}

//on click seeit button, log it to cookie
$('input.seeit').click(function(){
    var data = $(this).attr('name');
    if (!data) return;
    var itemLimit = 6;
    var rv = $.cookie('RecentlyViewed')||'';
    if (rv.split('*').length>=itemLimit) {
        //replace the first one
        rv = rv.substr(rv.indexOf('*')+1);
    }
    var s='';
    d = new Date(); 
    s += (d.getUTCMonth() + 1) + 'x'; 
    s += d.getUTCDate() + 'x'; 
    s += d.getUTCFullYear();
    if (rv.indexOf(data)==-1) {
        data += '-'+s;
        if(rv!='') data = '*'+data;
        $.cookie('RecentlyViewed', rv+data, cookieOpt);
    }
}).each(function(){
    var btn = $(this);
    var url = btn.attr('data');
    // use button click instead of link click, so we can save viewed data when user click a link
    $('a[href="'+url+'"]').click(function(){btn.click();return false;});
});

//seeit, compare button click event
$('input.seeit , input.compareprice').click(function(){
    var url = $(this).attr('data');
    if(url) window.open(url);
});

//show icon plus
if(sourceGroup!='google'){/*never show icon plus on google source*/
	$('td.t1 > div.imgbox > a > img').mouseover(function(){
	    $(this).parent().siblings('a:first').find('img[overlay]').show();
	}).mouseout(function(){
	    var rel = $(this).parent().siblings('a:first').find('img[overlay]');
	    var t = window.setTimeout(function(){rel.hide();},200);
	    rel.mouseover(function(){clearTimeout(t);})
	    .mouseout(function(){$(this).hide();});
	});
}

}); // end of documnet.onload