//! ################################################################
//! This file contains both original and merged/adapted code.
//! Except where indicated, all code is
//! Copyright (c) 2004-2006 Amazon.com, Inc., and its Affiliates.
//! All Rights Reserved.
//! Not to be reused without permission
//! ################################################################





amzn_adserver_url = "http://" + amzn_adserver_vip + "/d/?";


var amzn_LibraryStatus = {};

function amzn_cl_getOrgUnitID(){
	if(amzn_cl_mp == 'US'){
		return 1;
	}else if(amzn_cl_mp == 'GB'){
		return 2;
	}else if(amzn_cl_mp == 'DE'){
                return 3;
        }else if(amzn_cl_mp == 'FR'){
		return 8;
	}else if(amzn_cl_mp == 'CA'){
                return 15;
        }
}		
var amzn_cl_orgUnit = amzn_cl_getOrgUnitID();
var amzn_cl_constants = {
    linkStylePageDefault: 0,
    linkStyleNone: 1,
    linkStyleSingle: 2,
    linkStyleDouble: 3,
    linkStyleDashed: 4,
    linkSimilarProducts: 5,
    linkColorPageDefault: 'PD',
    linkIdPrefix: 'amzn_cl_link_'
};

var amzn_cl_previewData = {
    asinHasSimiliarProduct: {},
    aLinkElements: new Array()
};



var amzn_cl_bg_color_default = "FFFFFF";
var amzn_cl_border_color_default = "EFEDD4";
var amzn_cl_details_color_default = "000000";
var amzn_cl_product_link_color_default = "006699";
var amzn_cl_offered_price_color_default = "CC0000";
var amzn_cl_amazon_txt_color_default = "000000 ";

// Set our defaults.
var amzn_linkGenerator = {

    nServed: 0,
    nLinked: 0,
    invalidTags: {},
    populateInvalidTags : function() {
        this.invalidTags["TEXTAREA"] = true;
        this.invalidTags["SMALL"] = true;
        this.invalidTags["A"] = true;
        this.invalidTags["HEAD"] = true;
        this.invalidTags["TITLE"] = true;
        this.invalidTags["H1"] = true;
        this.invalidTags["H2"] = true;
        this.invalidTags["H3"] = true;
        this.invalidTags["H4"] = true;
        this.invalidTags["H5"] = true;
        this.invalidTags["H6"] = true;
        this.invalidTags[ "OPTION"] = true;
        this.invalidTags["STYLE"] = true;
        this.invalidTags["LINK"] = true;
        this.invalidTags["SCRIPT"] = true;
        this.invalidTags["COMMENT"] = true;
        this.invalidTags["#COMMENT"] = true;
        this.invalidTags["TH"] = true;
        this.invalidTags["TFOOT"] = true;
        this.invalidTags["INPUT"] = true;
        this.invalidTags["SELECT"] = true;
        this.invalidTags["DEL"] = true;
        this.invalidTags["STRIKE"] = true;
        this.invalidTags["S"] = true;
        this.invalidTags["TT"] = true;
        this.invalidTags["IMG"] = true;
        this.invalidTags["BUTTON"] = true;
        this.invalidTags["SUBMIT"] = true;
        this.invalidTags["ISINDEX"] = true;
        this.invalidTags["BLINK"] = true;
        this.invalidTags["DIR"] = true;
        this.invalidTags["KBD"] = true;
        this.invalidTags["LABEL"] = true;
        this.invalidTags["FIELDSET"] = true;
        this.invalidTags["LEGEND"] = true;
        this.invalidTags["MARQUEE"] = true;
        this.invalidTags["SUB"] = true;
        this.invalidTags["SUP"] = true;
        this.invalidTags["MENU"] = true;
        this.invalidTags["MAP"] = true;
        this.invalidTags["OBJECT"] = true;
        this.invalidTags["PARAM"] = true;
        this.invalidTags["SAMP"] = true;
        this.invalidTags["SERVER"] = true;
        this.invalidTags["BASE"] = true;
        this.invalidTags["ADDRESS"] = true;
        this.invalidTags["ACRONYM"] = true;
        this.invalidTags["PRE"] = true;
        this.invalidTags["AREA"] = true;
        this.invalidTags["APPLET"] = true;
        this.invalidTags["CAPTION"] = true;
        this.invalidTags["CODE"] = true;
        this.invalidTags["COL"] = true;
        this.invalidTags["COLGROUP"] = true;
        this.invalidTags["INS"] = true;
        this.invalidTags["OPTGROUP"] = true;
        this.invalidTags["THEAD"] = true;
        this.invalidTags["XMP"] = true;
        this.invalidTags["VAR"] = true;
    },
    creativesMap:[],
    initCreatives : function() {
        this.creativesMap[amzn_cl_constants.linkStylePageDefault + ':' + 0] = 9338;
        this.creativesMap[amzn_cl_constants.linkStylePageDefault + ':' + 1 + ':' + 0] = 9342;
	this.creativesMap[amzn_cl_constants.linkStylePageDefault + ':' + 1 + ':' + 1] = 11134;
        this.creativesMap[amzn_cl_constants.linkStyleNone + ':' + 0] = 9346;
        this.creativesMap[amzn_cl_constants.linkStyleNone + ':' + 1 + ':' + 0] = 9318;
	this.creativesMap[amzn_cl_constants.linkStyleNone + ':' + 1 + ':' + 1] = 11138;
        this.creativesMap[amzn_cl_constants.linkStyleSingle + ':' + 0] = 9350;
        this.creativesMap[amzn_cl_constants.linkStyleSingle + ':' + 1 + ':' + 0] = 9314;
	this.creativesMap[amzn_cl_constants.linkStyleSingle + ':' + 1 + ':' + 1] = 11142;
        this.creativesMap[amzn_cl_constants.linkStyleDouble + ':' + 0] = 9326;
        this.creativesMap[amzn_cl_constants.linkStyleDouble + ':' + 1 + ':' + 0] = 9334;
	this.creativesMap[amzn_cl_constants.linkStyleDouble + ':' + 1 + ':' + 1] = 11146;
        this.creativesMap[amzn_cl_constants.linkStyleDashed + ':' + 0] = 9322;
        this.creativesMap[amzn_cl_constants.linkStyleDashed + ':' + 1 + ':' + 0] = 9330;
	this.creativesMap[amzn_cl_constants.linkStyleDashed + ':' + 1 + ':' + 1] = 11150;
        this.creativesMap[amzn_cl_constants.linkSimilarProducts + ':' + 1] = 9358;
        this.creativesMap[amzn_cl_constants.linkBuyNow + ':' + 1] = 9354;
    },
    amzn_acToAWSCategoryMap: new Array(),
    initCategories: function() {
        this.amzn_acToAWSCategoryMap['a'] = "Books";
        this.amzn_acToAWSCategoryMap['b'] = "Music";
        this.amzn_acToAWSCategoryMap['c'] = "VHS,DVD,Video";
        this.amzn_acToAWSCategoryMap['d'] = "VideoGames";//"PC & Video Games";
        this.amzn_acToAWSCategoryMap['e'] = "Electronics,Photo,PCHardware";//Elektronik, Foto & Computer";
        this.amzn_acToAWSCategoryMap['f'] = "Software";
        this.amzn_acToAWSCategoryMap['p'] = "Toys";//"Spielwaren & Kinderwelt";
        this.amzn_acToAWSCategoryMap['h'] = "Electronics,Tools,Kitchen,HomeGarden";//"Küche, Haushalt & Garten";
    },
    amzn_cl_awsCategories : new Array(),
    initAWSCategories: function() {
        this.amzn_cl_awsCategories['Books'] = true;
        this.amzn_cl_awsCategories['Classical'] = true;
        this.amzn_cl_awsCategories['DVD'] = true;
        this.amzn_cl_awsCategories['Electronics'] = true;
        this.amzn_cl_awsCategories['ForeignBooks'] = true;
        this.amzn_cl_awsCategories['HealthPersonalCare'] = true;
        this.amzn_cl_awsCategories['HomeGarden'] = true;
        this.amzn_cl_awsCategories['Kitchen'] = true;
        this.amzn_cl_awsCategories['Magazines'] = true;
        this.amzn_cl_awsCategories['Music'] = true;
        this.amzn_cl_awsCategories['MusicTracks'] = true;
        this.amzn_cl_awsCategories['OutdoorLiving'] = true;
        this.amzn_cl_awsCategories['PCHardware'] = true;
        this.amzn_cl_awsCategories['Photo'] = true;
        this.amzn_cl_awsCategories['Software'] = true;
        this.amzn_cl_awsCategories['SoftwareVideoGames'] = true;
        this.amzn_cl_awsCategories['Tools'] = true;
        this.amzn_cl_awsCategories['Toys'] = true;
        this.amzn_cl_awsCategories['VHS'] = true;
        this.amzn_cl_awsCategories['Video'] = true;
        this.amzn_cl_awsCategories['VideoGames'] = true;
    },

    globalTimedOut : false,
    globalTimer: null,
    startGlobalTimer: function() {
        var date = new Date();
        this.globalTimer = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
    },
    isGlobalTimedOut: function() {
        var date = new Date();
        var curTime = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
        return (curTime - this.globalTimer) > 5000;
    },


    amazon_generate_url: function () {
        var amazon_q = amzn_adserver_url;
        amazon_q += "PublisherID=" + amzn_cl_tag;
        var escapedUrl = escape(document.location);
        escapedUrl = escapedUrl.replace(/[+]/g, "%2B");
        amazon_q += "&URL=" + escapedUrl;
        amazon_q += "&ResponseCount=" + amzn_cl_max_links;
        amazon_q += "&MarketPlace=" + amzn_cl_mp;
        amazon_q += "&ExactMatch=" + (amzn_cl_exact_match == 1);


        if (amzn_cl_categories != '') {
            amazon_q += "&CategoryRestriction=" + amzn_cl_categories;
        }
        return amazon_q;
    },


    amazon_fix_color:function ($color, $dflt) {
        if (!$color) {
            return $dflt;
        }
        if ($color.length != 6) {
            return $dflt;
        }
        $color = $color.toUpperCase();
        var $h2d = "0123456789ABCDEF";
        for (i = 0; i < 6; i++)
        {
            var $x = $color.charAt(i);
            if ($h2d.indexOf($x) == -1)
            {
                return $dflt;
            }
        }
        return $color;
    },
    amazon_pvid: function() {
        if (window.amazon_ad_pvid)
        {
            return amazon_ad_pvid;
        }

        amazon_ad_pvid = "";

        var $h2d = "0123456789ABCDEF";
        for (i = 0; i < 16; i++)
        {
            amazon_ad_pvid += $h2d.charAt(Math.floor(16 * Math.random()));
        }
    },

    isValidTag: function(node) {
        if (this.invalidTags[node.tagName]) {
            return false;
        }
        return this.hasValidOtherAttribs(node);
    },

    hasValidOtherAttribs:function(node) {
        while (node) {
            if (node.getAttribute) {
                if (node.getAttribute("onmouseover") || node.getAttribute("onmouseout")) {
                    return false;
                }
            }
            node = node.parentNode;
        }
        return true;
    },


    xpathQuery: function(data) {
        var xpath = data[XI];
        var context = data[CI];
        var a = xpath.split('/');
        for (var k = 0; k < a.length; k++) {
            if (a[k].indexOf("BODY") > -1) {
                break;
            }
        }
        a.splice(0, k + 1);
        var currentNode = document.getElementsByTagName("BODY")[0];
        while (a.length > 0 && currentNode != null) {
            var c = a[0];
            if (a.shift) {
                a.shift();
            }
            else
            {
                a.splice(0, 1);
            }
            var b = c.split(/\[|\]/);
            var tagName = b[0];
            var count = 1;
            oldNode = currentNode;
            if (b.length > 1) {
                count = b[1];
            }
            if (tagName.toUpperCase() == "#TEXT")continue;
            if (currentNode == null)continue;
            if (currentNode.tagName == "TABLE" && tagName == 'TR') {
                currentNode = currentNode.rows[count - 1];
                continue;
            }
            if (currentNode.tagName == "TR" && tagName == 'TD')
            {
                currentNode = currentNode.cells[count - 1];
                continue;
            }
            if (currentNode.tagName == "TABLE")
                continue;
            var size = currentNode.childNodes.length;
            for (j = 0; j < size; j++) {
                var child = currentNode.childNodes[j];
                if (child.nodeName.toUpperCase() == tagName)
                {
                    count--;
                    if (count == 0)
                    {
                        currentNode = child;
                        break;
                    }

                }
            }
            if (j == size) {
                break;
            }
        }

        return currentNode;
    },

    applyNodeIdMatch: function(i) {
        if (this.served_kwds[i][NI] != '') {
            var node = document.getElementById(this.served_kwds[i][NI]);
            var textNode = null;
            if (this.hasParentAOrScript(node))
                return false;
            if (node.hasChildNodes()) {
                for (var k = 0; k < node.childNodes.length; k++) {
                    if (node.childNodes[k] != null && node.childNodes[k].nodeType == 3) {
                        if ((textNode = this.locateTextNode(node.childNodes[k], this.served_kwds[i])) != null) {
                            if (this.insertATag(textNode, this.served_kwds[i])) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    },


    applyNodeNameMatch: function(i) {
        if (this.served_kwds[i][NN] != '') {
            var node = document.getElementsByName(this.served_kwds[i][NN]);
            var j = 0;
            while (j < node.length) {
                var textNode = null;
                if (this.hasParentAOrScript(node[j])) {
                    j++;
                    continue;
                }
                if (node[j].hasChildNodes()) {
                    for (var k = 0; k < node[j].childNodes.length; k++) {
                        if (node[j].childNodes[k] != null && node[j].childNodes[k].nodeType == 3) {
                            if ((textNode = this.locateTextNode(node[j].childNodes[k], this.served_kwds[i])) != null) {
                                if (this.insertATag(textNode, this.served_kwds[i])) {
                                    return true;
                                }
                            }
                        }
                    }
                }
                j++;
            }
        }
        return false;
    },

    applyXPathMatch:function(i) {
        var lastMatchNode = null;
        if (this.served_kwds[i][XI] != '') {
            lastMatchNode = this.xpathQuery(this.served_kwds[i]);
            if (lastMatchNode != null && (textNode = this.locateTextNode(lastMatchNode, this.served_kwds[i])) != null) {
                if (this.insertATag(textNode, this.served_kwds[i])) {
                    return null;
                }
            }
        }
        if (lastMatchNode == null) {
            lastMatchNode = 0;
        }
        return lastMatchNode;
    },


    applyXPathMisMatchFallBack: function(lastMatchNode, i) {
        var textNode = this.locateNode(lastMatchNode, this.served_kwds[i]);
        if (textNode != null) {
            if (this.insertATag(textNode, this.served_kwds[i])) {
                return true;
            }
        }
        return false;
    },

    applyNodeTagNameMatch:function() {

        var sameTagsAs0 = [];
        var i = 0;
        var data = this.served_kwds[i];
        var a = data[XI].split('/');
        var tagName = a[a.length - 2].split("[")[0];
	
        var obj = {};
        obj.index = 0;
        obj.data = data;
        sameTagsAs0[sameTagsAs0.length] = obj;
        if (this.doneTags[tagName]) {
            this.served_kwds.splice(0, 1);
            return false;
        }
        for (var j = 1; j < this.served_kwds.length; j++) {
            var data2 = this.served_kwds[j];
            var a2 = data2[XI].split('/');
            var tagName2 = a2[a2.length - 2].split("[")[0];
            if (tagName2 == tagName) {
                var obj = {};
                obj.index = j;
                obj.data = data2;
                sameTagsAs0[sameTagsAs0.length] = obj;
            }
        }
	var foundThis = false;
        var nodes = document.getElementsByTagName(tagName);
        if (nodes != null) {
		var i = 0;
		for(;i<nodes.length && sameTagsAs0.length > 0;i++){
			for(var k = 0; k < nodes[i].childNodes.length && sameTagsAs0.length > 0;k++){
				if(this.isGlobalTimedOut()){
			                return foundThis;
        			}
	
				if(nodes[i].childNodes[k].nodeType == 3){
					for(j = 0;j < sameTagsAs0.length;j++){
						if((textNode =this.locateTextNode(nodes[i].childNodes[k],sameTagsAs0[j].data))!= null){
							if(this.insertATag(textNode, sameTagsAs0[j].data)) {
								this.served_kwds.splice(sameTagsAs0[j].index, 1);
                                                                var ind = sameTagsAs0[j].index;
                                                                sameTagsAs0.splice(j, 1);
                                                                if(j == 0){
                                                                        foundThis = true;
                                                                }
                                                                for(var ct = j;ct < sameTagsAs0.length;ct++){
                                                                        if(sameTagsAs0[ct].index > ind){
                                                                                sameTagsAs0[ct].index--;
                                                                        }
                                                                }
                                                                j--;
							}
						}
					}
				}
				else{
					var nodeName = nodes[i].childNodes[k].nodeName;
					if(nodeName == 'P' || nodeName == 'SPAN' || nodeName == 'I' || nodeName == 'U' || nodeName == 'B' || 
						nodeName == 'UL' || nodeName == 'LI' || nodeName == 'FONT')
					{
						for(j = 0;j < sameTagsAs0.length;j++){
							if((textNode =this.locateNode(nodes[i].childNodes[k],sameTagsAs0[j].data))!= null){
        		                                	if(this.insertATag(textNode, sameTagsAs0[j].data)) {
									this.served_kwds.splice(sameTagsAs0[j].index, 1);
                                                                        var ind = sameTagsAs0[j].index;
                                                                        sameTagsAs0.splice(j, 1);
                                                                        if(j == 0){
                                                                                foundThis = true;
                                                                        }
                                                                        for(var ct = j;ct < sameTagsAs0.length;ct++){
                                                                                if(sameTagsAs0[ct].index > ind){
                                                                                        sameTagsAs0[ct].index--;
                                                                                }
                                                                        }
                                                                        j--;
                                        		        }
        		                                }
						}
					}
				}
						
			}
		}
	}
        this.doneTags[tagName] = true;
        return foundThis;
    },

    getValidTagName: function(a) {
        tagName = a[a.length - 3].split("[")[0];
        var process = false;
        if (tagName == 'FONT' || tagName == 'SPAN') {
            return tagName;
        } else if (a.length > 4 && tagName == 'P') {
            var newTagName = a[a.length - 4].split("[")[0];
            if (newTagName == 'FONT' || newTagName == 'SPAN') {
                return newTagName;
            } else {
                return newTagName;
            }
        }
        return null;
    },

    doneTags : {},

    maxKwd : "",

    logLinkedNumbers: function() {
        var img = document.createElement("IMG");
        img.setAttribute('style', "width: 1px; height: 1px;");
        img.src = "http://" + window.amzn_popovers_vip + "/e/lr?" +
                  '&amp;t=' + amzn_cl_tag +
                  '&amp;ls=' + this.nServed +
                  '&amp;al=' + amzn_cl_previewData.aLinkElements.length;
        document.body.appendChild(img);
        img = document.createElement("IMG");
        img.setAttribute('style', "width: 1px; height: 1px;");
        if (this.nServed > 0) {
            img.src = this.amazon_generate_url()
                    + "&Browser=" + navigator.appName
                    + "&Service=LinkFBService"
                    + "&Screen=" + this.getScreenCoords()
                    + "&Pos=" + this.getMaxKwdCoodrs()
                    + "&Kwd=" + this.maxKwd;
            document.body.appendChild(img);
        }

    },


    getScreenCoords: function() {
        var coords = "";
        var sw = 0, sh = 0;
        if (typeof( window.innerWidth ) == 'number') {
            sw = window.innerWidth;
            sh = window.innerHeight;
        } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
            sw = document.documentElement.clientWidth;
            sh = document.documentElement.clientHeight;
        } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
            sw = document.body.clientWidth;
            sh = document.body.clientHeight;
        }
        return sw + "X" + sh;
    },
    linkedKwd: new Object(),
    getMaxKwdCoodrs:function () {
        var maxATag = null;
        var maxCoords = null;
        var maxProd = 0;
        for (var j = 0; j < amzn_cl_previewData.aLinkElements.length; j++) {
            var curATag = amzn_cl_previewData.aLinkElements[j];
            var coords = this.getCoords(curATag);
            var prod = coords[0] * coords[1] ;
            if (prod > maxProd) {
                maxProd = prod;
                maxCoords = coords[0] + "X" + coords[1];
                maxATag = curATag;
            }
        }
        if (amzn_cl_previewData.aLinkElements.length > 0) {
            this.maxKwd = this.linkedKwd[maxATag];
            return maxCoords;
        } else {
            this.maxKwd = "";
            return "0X0";
        }
    },

    getCoords: function(aTag) {
        var left = 0;
        var top = 0;
        while (aTag.offsetParent) {
            left = left + aTag.offsetLeft;
            top = top + aTag.offsetTop;
            aTag = aTag.offsetParent;
        }
        return [left,top];
    },


    locateNode: function (node, data, level) {
	if(this.isGlobalTimedOut()){
                return null;
        }
        if(typeof(level) == 'undefined'){
                level = 0;
        }
        if(level > 5){
                return null;
        }
        level++;
	var textNode = null;
        if (node == null)
            return null;
        if (node.childNodes != null && node.childNodes.length > 0) 
	{
		var nodeName = node.nodeName;
		if(nodeName == 'P' || nodeName == 'SPAN' || nodeName == 'I' || nodeName == 'U' || nodeName == 'B' ||
            	nodeName == 'UL' || nodeName == 'LI' || nodeName == 'FONT' )
		{	
	         	for (var k = 0; k < node.childNodes.length; k++) {
                		var textNode = this.locateNode(node.childNodes[k], data, level);
		                if (textNode != null) {
        		            return textNode;
                		}
	            	}
	   	}			
        }else {
            if ((textNode = this.locateTextNode(node, data)) != null) {
                return textNode;
            }
        }
        return null;
    },

    checkForMatch:function(str, data) {
        var ind = this.findExactWordInd(str, data);
        return ind;
    },
    findExactWordInd: function(str, data) {
        var kwd = data[PI].toLowerCase();
        var occCount = data[OCI];
        var splitted = str.split(kwd);
        var ind = -1;
        if (splitted.length == 1 && occCount > 1) {
            var newkwd = this.checkAgain(str, kwd, occCount);
            if (newkwd == '') {
                return -1;
            } else {
                kwd = newkwd;
                data[PI] = kwd;
                splitted = str.replace(/\n/g, ' ').split(kwd);
            }
        }
        else if (splitted.length <= 1) {
            ind = str.indexOf(kwd);
            if (ind == -1) {
                var newkwd = this.checkAgain(str, kwd, occCount);
                if (newkwd == '') {
                    return -1;
                } else {
                    kwd = newkwd;
                    data[PI] = kwd;
                    splitted = str.replace(/\n/g, ' ').split(kwd);
                }

            } else {
                return ind;
            }
        }
        if (splitted.length <= occCount)/*occ =2 is first so lenght must be atleast 2*/{
            var newkwd = this.checkAgain(str, kwd.occCount);
            if (newkwd == '') {
                return -1;
            } else {
                kwd = newkwd;
                data[PI] = kwd;
                splitted = str.replace(/\n/g, ' ').split(kwd);
            }

        }
        if (occCount == 0)occCount = 1;
        var j = occCount;
        var nextChar = splitted[j].charAt(0);
        var prevChar = (splitted[j - 1].length > 0 )? splitted[j - 1].charAt(splitted[j - 1].length - 1):"";
        if (prevChar == '' || (prevChar.isNotAlphaNum() && prevChar != '-')) {
            if (nextChar == '' || (nextChar.isNotAlphaNum() && nextChar != '-'))
            {
                var k = 0;
                while (k < j) {
                    ind += splitted[k].length;
                    k++;
                }

                ind += (j - 1) * kwd.length + 1;
                if (ind + kwd.length > str.length)
                    ind = -1;
            }
        }

        return ind;

    },

    checkAgain: function (str, kwd, occCount) {
        var str1 = str.replace(/[\t \s]*[\n\r][\s\t ]*/g, " ");
        if (str == str1) {
            return '';
        }
        else if (str1.indexOf(kwd) < 0) {
            return '';
        }
        var words = kwd.split(" ");
        if (words.length == 1) {
            return '';
        }
        str = str.replace(/\n/g, " ");
        var nodeWords = str.split(words[0]);
        if (nodeWords.length <= occCount) {
            return '';
        }
        if (occCount == 0)occCount = 1;
        var index = -1;
        var n = 0;
        while (occCount > 0 && n < nodeWords.length) {
            var k = 1;
            while (n < nodeWords.length) {
                if (nodeWords[n].indexOf(words[k]) > -1) {
                    var thisWords = nodeWords[n++].split(/[\s\t ]+/);
                    if (thisWords.length == 1) {
                        return -1;
                    }
                    var l = 0;
                    for (l = 0; l < thisWords.length && k < words.length; l++) {
                        if (thisWords[l] == '') {
                            continue;
                        }
                        if (words[k] != thisWords[l]) {
                            break;
                        }
                        k++;
                    }
                    if (k < words.length) {
                        break;
                    }
                    occCount--;
                    if (occCount > 0) {
                        break;
                    }
                    var m = 1;
                    var thisInd = -1;
                    while (m < l) {
                        thisInd = nodeWords[n - 1].indexOf(thisWords[m++], thisInd + 1);
                    }
                    if (m == l) {
                        var endIndex = thisInd + thisWords[m - 1].length + words[0].length;
                        var beginIndex = 0;
                        if (n > 1) {
                            if (n - 1 > 0) {
                                beginIndex += nodeWords[0].length;
                            }
                            for (p = 1; p < n - 1; p++) {
                                beginIndex += words[0].length;
                                beginIndex += nodeWords[p].length;
                            }
                            return str.substring(beginIndex, endIndex);

                        }
                    }
                } else {
                    n++;
                }
            }
        }
        return '';
    },
    hasParentAOrScript: function(node) {
        var pN = node;
        while (pN && pN != null && pN != document.documentElement) {
            if (pN.nodeName == "A" || pN.nodeName == "SCRIPT")
                return true;
            pN = pN.parentNode;
        }
        return false;
    },

    trim: function(txt)
    {
        if (txt == null)
            return txt;
        txt = txt.replace(/&nbsp(;?)/g, " ");
        txt = txt.replace(/[\n\r]+/g, " ");
        txt = txt.replace(/^[\s\t ]*/g, "");
        txt = txt.replace(/[\s\t ]*$/g, "");
        txt = txt.replace(/[\s\t ]+/g, " ");
        return txt;

    },


    locateTextNode:function(node, data) {
        var j = 0;
        context = data[CI];
        var nodeValue = null;
        var cond = false;
        var returnNode = null;
        if (node.nodeType == 3) {
            nodeValue = node.nodeValue;
            if (nodeValue != null) {
                nodeValue = nodeValue.replace(/[ \t\s]*[\n\r][ \t\s]*/g, " ");
                var contextIndex = this.trim(nodeValue).indexOf(this.trim(context));
                if (contextIndex > -1 && contextIndex < 5) {
                    returnNode = node;
                }
            }
        }
        return returnNode;
    },


    insertATag:function (node, data) {
        if (this.numKeywordsLinked >= amzn_cl_max_links)
            return false;

        if (!this.isValidTag(node))
            return false;
        var pN = node.parentNode;
        if (this.hasParentAOrScript(pN))
            return false;
        var str = node.nodeValue;
        var a = document.createElement("A");
        var ind = this.checkForMatch(str.toLowerCase(), data);
        str = str.replace(/\n/g, ' ');
        if (ind == -1) {
            return false
        }
        var leftStr = str.substring(0, ind);
        var rightStr = str.substring(ind + data[PI].length, str.length);
        var txt = str.substring(ind, ind + data[PI].length);
        var t1 = null,t2 = null;
        t1 = document.createTextNode(leftStr);
        t2 = document.createTextNode(rightStr);
        a.href = this.getLandingUrl(data);
        this.setATagParameters(a);
        this.setPopoverParameters(a, data);
        a.innerHTML = txt;
        pN.replaceChild(t2, node);
        pN.insertBefore(a, t2);
        pN.insertBefore(t1, a);
        this.numKeywordsLinked++;
        this.recordImpression(data);
        amzn_cl_previewData.aLinkElements[amzn_cl_previewData.aLinkElements.length] = a;
        this.linkedKwd[a] = txt;
        return true;
    },

    setATagParameters:function (a) {
        if (amzn_cl_link_target) {
            a.target = '_blank';
        }

        var aColor = '';
        if (amzn_cl_link_color != amzn_cl_constants.linkColorPageDefault) {
            aColor = '#' + amzn_cl_link_color;
            a.style.color = aColor;
            aColor = ' ' + aColor;
        }

        if (amzn_cl_link_style != amzn_cl_constants.linkStylePageDefault) {
            switch (amzn_cl_link_style) {
                case amzn_cl_constants.linkStyleNone:
                    a.style.textDecoration = 'none';
                    break;
                case amzn_cl_constants.linkStyleSingle:
                    a.style.textDecoration = 'underline';
                    break;
                case amzn_cl_constants.linkStyleDouble:
                    a.style.textDecoration = 'underline';
                    a.style.borderBottom = '1px solid';
                    a.style.paddingBottom = '1px';
                    break;
                case amzn_cl_constants.linkStyleDashed:
                    a.style.textDecoration = 'none';
                    a.style.borderBottom = '1px dashed';
                    break;
            }
        }
    },

    getcreativeMap: function(){
     var creativeMap;
	if(amzn_cl_preview)
	{
		creativeMap = amzn_cl_link_style + ':' + amzn_cl_preview + ':' + amzn_cl_show_buy_btn;
	}
	else
	{
		creativeMap = amzn_cl_link_style + ':' + amzn_cl_preview;
	}
	return creativeMap;
    },

    getLandingUrl: function(data) {
        var url = "http://" +amzn_cl_amzn_site + "/gp/product/" + data[AI] + "?ie=UTF8";
        url += "&tag=" + amzn_cl_tag;
        url += "&link_code=em1";
        url += "&camp=" + amzn_cl_camp_id;
        url += "&creative=" + this.creativesMap[this.getcreativeMap()];
        url += "&creativeASIN=" + data[AI];
        url += '&adid=' + data[IID];

        return url;
    },


    link_id: 0,

    setPopoverParameters: function(a, data) {
        a.id = amzn_cl_constants.linkIdPrefix + this.link_id++;
        a.name = data[AI];
    },

    getScriptTag: function(src) {
        var scpt = document.createElement("SCRIPT");
        scpt.src = src;
        scpt.type = 'text/javascript';
	scpt.charset = amzn_cl_js_encoding;
        return scpt;
    },

    callPopOvers: function() {
        if (amzn_cl_preview != 0) {
            if (!document.getElementById("amzn_cl_popup_css")) {
                var objHead = document.getElementsByTagName('head');
                if (objHead[0]) {
                    var stylesheetObj;
                    if (document.createElementNS && objHead[0].tagName == 'head') {
                        stylesheetObj = document.createElementNS('http://www.w3.org/1999/xhtml', 'link');
                    } else {
                        stylesheetObj = document.createElement('link');
                    }
                    stylesheetObj.id = 'amzn_cl_popup_css';
                    stylesheetObj.rel = 'stylesheet';
                    stylesheetObj.href = 'http://' + amzn_popovers_vip + '/images/popover.css';
                    stylesheetObj.type = 'text/css';
                    objHead[0].appendChild(stylesheetObj);
                }
            }

            document.body.appendChild(this.getScriptTag('http://' + amzn_popovers_vip + '/' + amzn_cl_dir + '/popover/popup.js'));
            document.body.appendChild(this.getScriptTag('http://' + amzn_popovers_vip + '/' + amzn_cl_dir + '/popover/previewManager.js'));
        }
    },


    recordImpression:function(data) {
        var img = document.createElement("IMG");
        img.setAttribute('style', "width: 1px; height: 1px;");
        img.src = "http://" + amzn_cl_sAssocImpVIP + "/e/ir?" +
                  'o=' + amzn_cl_orgUnit + 
                  '&amp;t=' + amzn_cl_tag +
                  '&amp;l=em1' +
                  '&amp;a=' + data[AI] +
                  '&amp;creative=' + this.creativesMap[this.getcreativeMap()];
        document.body.appendChild(img);
    },

    initAmznPreviewManager:function() {
        amzn_LibraryStatus.updateLinksLoaded = true;
        if (typeof(amzn_LibraryStatus.previewManagerLoaded) != 'undefined' &&
            amzn_LibraryStatus.previewManagerLoaded) {
            amzn_previewManager.init();
        }
    },

    amzn_fix_boolean_params: function(param, defaultValue) {
        var result;

        if (typeof(param) == 'undefined' || param < 0 || param > 1) {
            result = defaultValue;
        } else {
            result = param;
        }

        return result;
    },

    getAwsCategory:function(cat) {
        var result = this.amzn_acToAWSCategoryMap[cat];
        if (typeof(result) == 'undefined') {
            var isValid = this.amzn_cl_awsCategories[cat];
            if (typeof(isValid) != 'undefined' && isValid) {
                result = cat;
            }
        }

        return result;
    },

    setDefaultsValidateParameters:function() {
        if (!window.amzn_cl_tag) {
            return false;
        }
        amzn_cl_link_color = this.amazon_fix_color(window.amzn_cl_link_color, amzn_cl_constants.linkColorPageDefault);

        if (!window.amzn_cl_link_style) {
            amzn_cl_link_style = amzn_cl_constants.linkStylePageDefault;
        } else if (amzn_cl_link_style != amzn_cl_constants.linkStyleSingle &&
                   amzn_cl_link_style != amzn_cl_constants.linkStyleDouble &&
                   amzn_cl_link_style != amzn_cl_constants.linkStyleDashed &&
                   amzn_cl_link_style != amzn_cl_constants.linkStyleNone &&
                   amzn_cl_link_style != amzn_cl_constants.linkStylePageDefault) {
            amzn_cl_link_style = amzn_cl_constants.linkStylePageDefault;
        }

        amzn_cl_link_target = this.amzn_fix_boolean_params(window.amzn_cl_link_target, 1);
        amzn_cl_preview = this.amzn_fix_boolean_params(window.amzn_cl_preview, 1);
        amzn_cl_logo = this.amzn_fix_boolean_params(window.amzn_cl_logo, 1);
        amzn_cl_product_image = this.amzn_fix_boolean_params(window.amzn_cl_product_image, 1);
        amzn_cl_list_price = this.amzn_fix_boolean_params(window.amzn_cl_list_price, 1);
        amzn_cl_offered_price = this.amzn_fix_boolean_params(window.amzn_cl_offered_price, 1);
        amzn_cl_average_customer_rating = this.amzn_fix_boolean_params(window.amzn_cl_average_customer_rating, 1);

        amzn_cl_bg_color = this.amazon_fix_color(window.amzn_cl_bg_color, amzn_cl_bg_color_default);
        amzn_cl_border_color = this.amazon_fix_color(window.amzn_cl_border_color, amzn_cl_border_color_default);
        amzn_cl_details_color = this.amazon_fix_color(window.amzn_cl_details_color, amzn_cl_details_color_default);
        amzn_cl_product_link_color = this.amazon_fix_color(window.amzn_cl_product_link_color, amzn_cl_product_link_color_default);
        amzn_cl_offered_price_color = this.amazon_fix_color(window.amzn_cl_offered_price_color, amzn_cl_offered_price_color_default);
        amzn_cl_amazon_txt_color = this.amazon_fix_color(window.amzn_cl_amazon_txt_color, amzn_cl_amazon_txt_color_default);

        amzn_cl_exact_match = this.amzn_fix_boolean_params(window.amzn_cl_exact_match, 0);
	amzn_cl_show_buy_btn = this.amzn_fix_boolean_params(window.amzn_cl_show_buy_btn, 1);

        if (typeof(amzn_cl_max_links) == 'undefined') {
            amzn_cl_max_links = 10;
        } else {
            amzn_cl_max_links = (amzn_cl_max_links > 20 || amzn_cl_max_links < 1) ? 10 : amzn_cl_max_links;
        }

        if (!window.amzn_cl_categories || amzn_cl_categories == null) {
            amzn_cl_categories = '';
        } else {
            var cats = amzn_cl_categories.split(',');
            amzn_cl_categories = '';
            if (cats.length > 0) {
                for (var i = 0; i < cats.length; i++) {
                    if (cats[i] == '') {
                        continue;
                    }
                    if (cats[i] == 'Blended') {
                        amzn_cl_categories = '';
                        break;
                    }
                    var cat = this.getAwsCategory([cats[i]]);
                    if (typeof(cat) != 'undefined') {
                        amzn_cl_categories += ',' + cat;
                    } else {
                        amzn_cl_categories = '';
                        break;
                    }
                }
                amzn_cl_categories = amzn_cl_categories.substring(1);
                //To remove the first comma
            }
        }

        return true;
    },

    numKeywordsLinked: 0,
    createRequest:function() {
        this.amazon_pvid();

        document.body.appendChild(this.getScriptTag(this.amazon_generate_url()));
    },

    init: function() {
        amzn_linkGenerator.populateInvalidTags();
        amzn_linkGenerator.initCreatives();
        amzn_linkGenerator.initCategories();
        amzn_linkGenerator.initAWSCategories();
        if (!amzn_linkGenerator.setDefaultsValidateParameters()) {
            return;
        }
        amzn_linkGenerator.createRequest();
        amzn_linkGenerator.callPopOvers();
    },
    served_kwds:[],
    updateLinks:function(kwds) {
        this.served_kwds = kwds;
        var i = 0;
        this.nServed = this.served_kwds.length;
        this.nLinked = this.nServed - this.served_kwds.length;
        this.startGlobalTimer();
        this.setLinks();
    },
    setLinks:function() {
        if (this.served_kwds.length == 0) {
            this.initAmznPreviewManager();
            this.logLinkedNumbers();
            return;
        }
        if (this.numKeywordsLinked >= amzn_cl_max_links) {
            this.initAmznPreviewManager();
            this.logLinkedNumbers();
            return;
        }
        var found = true;
        if (!this.applyNodeIdMatch(0)) {
            if (!this.applyNodeNameMatch(0)) {
                var lastMatchNode = this.applyXPathMatch(0);

                if (lastMatchNode != null) {
                    if (!this.applyNodeTagNameMatch()) {
                        //if (lastMatchNode != 0 && this.served_kwds.length > 0) {
                          //  if (lastMatchNode != null && lastMatchNode.nodeName != 'BODY') {
                                //if (!this.applyXPathMisMatchFallBack(lastMatchNode, 0)) {
                                    found = false;
                                //}
                            //}
                        //}
                    }
                }
            }
        }
        if (!found && this.served_kwds.length > 0) {
            this.served_kwds.splice(0, 1);
        }

        if (!this.isGlobalTimedOut()) {
            this.setLinks();
        } else {
            this.initAmznPreviewManager();
            this.logLinkedNumbers();
        }
    }

};


String.prototype.isNotAlphaNum = function () {
    return (/[^a-zA-Z0-9]/.test(this));
}


function getNodeText()
{
    window.amzn_kwds = [];
    var i = 0;
    for (i = 0; i < kwds.length; i++)
    {
        kwds[i][PI] = amzn_linkGenerator.trim(kwds[i][PI]);
        kwds[i][CI] = amzn_linkGenerator.trim(kwds[i][CI]);
        amzn_kwds[i] = kwds[i][PI];
        amzn_cl_previewData.asinHasSimiliarProduct[kwds[i][AI]] = kwds[i][SP];
    }

    amzn_linkGenerator.updateLinks(kwds);
}

amzn_linkGenerator.init();

