/*
	This JSON script can be found in it's original form here:
	http://www.json.org/json2.js
	
	I've removed the comments to make it more compact
*/

if (!this.JSON) {

    JSON = function () {

        function f(n) {
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };

        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            gap,
            indent,
            meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            },
            rep;


        function quote(string) {

            escapeable.lastIndex = 0;
            return escapeable.test(string) ?
                '"' + string.replace(escapeable, function (a) {
                    var c = meta[a];
                    if (typeof c === 'string') {
                        return c;
                    }
                    return '\\u' + ('0000' +
                            (+(a.charCodeAt(0))).toString(16)).slice(-4);
                }) + '"' :
                '"' + string + '"';
        }


        function str(key, holder) {

            var i,          // The loop counter.
                k,          // The member key.
                v,          // The member value.
                length,
                mind = gap,
                partial,
                value = holder[key];

            if (value && typeof value === 'object' &&
                    typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }

            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }

            switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                return String(value);

            case 'object':

                if (!value) {
                    return 'null';
                }

                gap += indent;
                partial = [];

                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +
                                    mind + ']' :
                              '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
            }
        }

        return {
            stringify: function (value, replacer, space) {

                var i;
                gap = '';
                indent = '';

                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }

                } else if (typeof space === 'string') {
                    indent = space;
                }

                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                        (typeof replacer !== 'object' ||
                         typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }

                return str('', {'': value});
            },


            parse: function (text, reviver) {

                var j;

                function walk(holder, key) {

                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }

                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' + ('0000' +
                                (+(a.charCodeAt(0))).toString(16)).slice(-4);
                    });
                }

                if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                    j = eval('(' + text + ')');

                    return typeof reviver === 'function' ?
                        walk({'': j}, '') : j;
                }

                throw new SyntaxError('JSON.parse');
            }
        };
    }();
}

// only include this script if we haven't already defined it
if(!this.TAGGA) {

	var TAGGA = true;
	
	// borrowed/modified from prototype...everything renamed tagga-like in order to 
	//  avoid conflicts with any included prototype script...if any
	var TaggaBrowser = {
	
		IE:     !!(window.attachEvent && !window.opera),
		Opera:  !!window.opera,
		WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
		Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
		MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
	};
	
	function _taggaReturnOffset(l, t) {
	
	  var result = [l, t];
	  result.left = l;
	  result.top = t;
	  return result;
	}
	
	function _taggaCumulativeOffset(element) {
	
		var valueT = 0, valueL = 0;
		do {
		
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		
		return _taggaReturnOffset(valueL, valueT);
	}
	
	document.taggaViewport = {
		
		getDimensions: function() {
		
			var dimensions = { };
			var B = TaggaBrowser;
			
			dimensions['width'] = (B.WebKit && !document.evaluate) ? self['innerWidth'] :
			    (B.Opera) ? document.body['clientWidth'] : document.documentElement['clientWidth'];
			    
			dimensions['height'] = (B.WebKit && !document.evaluate) ? self['innerHeight'] :
			    (B.Opera) ? document.body['clientHeight'] : document.documentElement['clientHeight'];
			
			return dimensions;
		},
		
		getWidth: function() {
		
			return this.getDimensions().width;
		},
		
		getHeight: function() {
		
			return this.getDimensions().height;
		},
		
		getScrollOffsets: function() {
			
			return _taggaReturnOffset(
			  window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
			  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
		}
	};
	// END borrowed from prototype
	
	
	
	// insert style for our divs
	document.write("\r\n\u003Cstyle type=\"text/css\"\u003E\r\n#tagga_popup {\r\n  z-index:105; background:url(http://dev.tagga.com/img/partner/bg-sendtomobile.png) no-repeat;" + 
		"  \r\n}\r\n#tagga_background {\r\n  position: fixed;\r\n" + 
		"  z-index:100;\r\n  top: 0;\r\n  left: 0;\r\n" + 
		"  right: 0;\r\n  bottom: 0;\r\n  background-color: #000;\r\n  opacity: .7;\r\n  filter:" + 
		" alpha(opacity=70);\r\n}\r\n\u003C/style\u003E\r\n");
	
	// global vars
	var taggaScriptUrl = '';
	var taggaKey = '';
	var taggaRssUrl = null;
	
	function taggaGetElementsByName(tagName) {
	
		var theElements = new Array();
		
		var allDivs = document.getElementsByTagName("div");
		if(allDivs != null) {
		
			for(var ii = 0; ii < allDivs.length; ii++) {
			
				if(allDivs[ii].getAttribute("name") == tagName) {
			
					theElements.push(allDivs[ii]);
				}
			}
		}
	 
		return theElements;
	}
	
	function getStyleForElement(element) {
	
		var styleStr = '';
		if(element != null) {
		
			styleStr = element.getAttribute('style');
			if(styleStr != null) {
			
				if(typeof styleStr != 'string') {
				
					if(typeof styleStr == 'object') {
				
						styleStr = styleStr.cssText;
					} else { // shouldn't get here, but just in case...
					
						styleStr = '';
					}
				}
			} else {
			
				styleStr = '';
			}
		}
		
		return styleStr;
	}
	
	function taggaOnLoad() {
	
		// extract parameters from the JS script
		extractJsParams();
		
		// create the popup div
		createPopupDiv();
		
		var encoding = getPageEncoding();

		// --- DEPRECATED --- we should promote div with name="tagga_rss" so you can create multiple RSS links on a single page
		
		// *** Create a RSS or tagg Link ***
		// find the div element where the link will be injected
		var linkElement = document.getElementById('tagga_rss');

		// make sure it's a div if we found it
		if(linkElement != null && linkElement.tagName.toLowerCase() == 'div') {
	
			// create the link for the iframe
			var taggaUrl = createTaggaUrl('', '', taggaKey, '', encoding);
			
			// we don't allow the user to change the title for an RSS feed
			var taggaCustomTitle = 'Subscribe to Mobile'
			
			// get any custom style
			var taggaCustomStyle = getStyleForElement(linkElement);
			if(taggaCustomStyle.length > 0) {
			
				linkElement.removeAttribute('style');
			}
			
			// append the image and link to the element given to us
			linkElement.appendChild(
				createTaggaLink(taggaCustomTitle, 
					taggaCustomStyle, 
					'tagga_link',
					taggaUrl)
				);
		} // *** END Create a RSS or tagg Link ***
		// --- END DEPRECATED ---
		
		// *** Create RSS links ***
		var rssList = taggaGetElementsByName('tagga_rss');
		if(rssList != null) {
		
			var counter = 0; // use this to create different link IDs
			for(var ii = 0; ii < rssList.length; ii++) {
			
				// make sure it's a div, if not, disregard it
				if(rssList[ii].tagName.toLowerCase() == 'div') {
				
					// clear out the inner html, we will replace it
					rssList[ii].innerHTML = '';
				
					// create the tagga RSS link URL...do this once since we re-use for RSS (only 1 RSS per page)
					if(taggaRssUrl == null) {
					
						taggaRssUrl = createTaggaUrl('', '', taggaKey, '', encoding);
					}
					
					// we don't allow the user to change the title for an RSS feed
					var taggaCustomTitle = 'Subscribe to Mobile'
					
					// get any custom style
					var taggaCustomStyle = getStyleForElement(rssList[ii]);
					if(taggaCustomStyle.length > 0) {
					
						rssList[ii].removeAttribute('style');
					}
					
					var taggaId = 'tagga_rss_' + counter;
					
					rssList[ii].appendChild(
						createTaggaLink(taggaCustomTitle, 
							taggaCustomStyle, 
							taggaId,
							taggaRssUrl)
						);
						
					counter++;
				}
			}
		} // *** END Create RSS links ***
		
		// *** Create custom content links ***
		// find all div elements that have the custom name...these are custom content tags
		var customContentList = taggaGetElementsByName('tagga_custom');
		if(customContentList != null) {
		
			// foreach custom tagg, create a link
			var counter = 0; // use this to create different link IDs
			for(var ii = 0; ii < customContentList.length; ii++) {
			
				// make sure it's a div, if not, disregard it
				if(customContentList[ii].tagName.toLowerCase() == 'div') {
				
					var customContent = customContentList[ii].innerHTML;
					if(customContent.length > 0) {
					
						// clear out the inner html, we will replace it
						customContentList[ii].innerHTML = '';
						
						// get any custom title specified
						var taggaCustomTitle = customContentList[ii].getAttribute('title');
						if(taggaCustomTitle == null || taggaCustomTitle.length <= 0) {
						
							taggaCustomTitle = 'Send to Mobile';
						}
						
						// get any custom style
						var taggaCustomStyle = getStyleForElement(customContentList[ii]);
						if(taggaCustomStyle.length > 0) {
						
							customContentList[ii].removeAttribute('style');
						}
					
						// create the link for the iframe
						var taggaUrl = createTaggaUrl('', customContent, taggaKey, '', encoding);
						var taggaId = 'tagga_custom_' + counter;
						
						customContentList[ii].appendChild(
							createTaggaLink(taggaCustomTitle, 
								taggaCustomStyle, 
								taggaId,
								taggaUrl)
							);
						
						counter++;
					}
				}
			}
		} // *** END Create custom content links ***
		
		// *** Create tagg links ***
		// find all div elements that have the custom name...these are custom content tags
		var taggList = taggaGetElementsByName('tagga_tagg');
		if(taggList != null) {
		
			// foreach custom tagg, create a link
			var counter = 0; // use this to create different link IDs
			for(var ii = 0; ii < taggList.length; ii++) {
			
				// make sure it's a div, if not, disregard it
				if(taggList[ii].tagName.toLowerCase() == 'div') {
				
					var taggContent = taggList[ii].innerHTML;
					if(taggContent.length > 0) {
					
						// clear out the inner html, we will replace it
						taggList[ii].innerHTML = '';
						
						// get any custom title specified
						var taggaCustomTitle = taggList[ii].getAttribute('title');
						if(taggaCustomTitle == null || taggaCustomTitle.length <= 0) {
						
							taggaCustomTitle = 'Send to Mobile';
						}
						
						// get any custom style
						var taggaCustomStyle = getStyleForElement(taggList[ii]);
						if(taggaCustomStyle.length > 0) {
						
							taggList[ii].removeAttribute('style');
						}
					
						// create the link for the iframe
						var taggaUrl = createTaggaUrl(taggContent, '', taggaKey, '', encoding);
						var taggaId = 'tagga_tagg_' + counter;
						
						taggList[ii].appendChild(
							createTaggaLink(taggaCustomTitle, 
								taggaCustomStyle, 
								taggaId,
								taggaUrl)
							);
						
						counter++;
					}
				}
			}
		} // *** END Create tagg data links ***
		
		// *** Create tagg links ***
		// find all div elements that contain custom taggs that can be added to our site dynamically
		var dynamicTaggList = taggaGetElementsByName('tagga_data');
		if(dynamicTaggList != null) {
		
			// foreach dynamic tagg, process and create a link
			var counter = 0; // use this to create different link IDs
			for(var ii = 0; ii < dynamicTaggList.length; ii++) {
			
				if(dynamicTaggList[ii].tagName.toLowerCase() == 'div') {
				
					var taggaJsonStr = processTaggaDataDiv(dynamicTaggList[ii]);
					
					// clear out the inner html, we will replace it with a link
					dynamicTaggList[ii].innerHTML = '';
					
					// get any custom title specified
					var taggaCustomTitle = dynamicTaggList[ii].getAttribute('title');
					if(taggaCustomTitle == null || taggaCustomTitle.length <= 0) {
					
						taggaCustomTitle = 'Send to Mobile';
					}
					
					// get any custom style
					var taggaCustomStyle = getStyleForElement(dynamicTaggList[ii]);
					if(taggaCustomStyle.length > 0) {
					
						dynamicTaggList[ii].removeAttribute('style');
					}
					
					// create the link for the iframe
					var taggaUrl = createTaggaUrl('', '', taggaKey, taggaJsonStr, encoding);
					var taggaId = 'tagga_data_' + counter;
					
					dynamicTaggList[ii].appendChild(
						createTaggaLink(taggaCustomTitle, 
							taggaCustomStyle, 
							taggaId,
							taggaUrl)
						);
					
					counter++;
				}
			}
		} // *** END Create tagg data links ***
	}
	
	function getPageEncoding() {
	
		var encoding = '';
		var charsetRegEx = /charset\s?=\s?[\w-]+/gi;
		
		var metaTagList = document.getElementsByTagName('meta');
		if(metaTagList != null) {
		
			for(var ii = 0; ii < metaTagList.length; ii++) {
			
				// only get the tag with the http-equiv attribute set to 'Content-Type'
				var httpEquivAttr = metaTagList[ii].getAttribute('http-equiv');
				if(httpEquivAttr != null && httpEquivAttr.toLowerCase() == 'content-type') {
				
					// extract the charset from the content
					var metaContent = metaTagList[ii].getAttribute('content');
					if(metaContent != null) {
					
						var matches = metaContent.match(charsetRegEx);
						if(matches != null && matches.length > 0) {
						
							var splitStr = matches[0].split('=');
							encoding = splitStr[1];
						}
					}
				}
			}
		}
		
		return encoding;
	}
	
	function createTaggaLink(linkText, linkStyle, linkId, linkUrl) {
	
	
		var taggaLink = document.createElement('a');
		taggaLink.setAttribute('id', linkId);
		
		// remove any display: none, we use this to hide the original content on page load
		taggaLink.style.cssText = linkStyle.replace(/display:[ ]{0,10}none;?/gi, '');
		taggaLink.setAttribute('href', 'javascript:showPopup(\'' + linkUrl + '\', \'' + linkId + '\');');
		taggaLink.innerHTML = linkText;
		
		/*var taggaLinkTd = document.createElement('td');
		taggaLinkTd.setAttribute('valign', 'middle');
		taggaLinkTd.appendChild(taggaLink);
		
		var taggaRow = document.createElement('tr');
		taggaRow.setAttribute('valign', 'middle');
		taggaRow.appendChild(taggaImageTd);
		taggaRow.appendChild(taggaLinkTd);
		
		var taggaTableBody = document.createElement('tbody');
		taggaTableBody.setAttribute('valign', 'middle');
		taggaTableBody.appendChild(taggaRow);
		
		var taggaTable = document.createElement('table');
		taggaTable.appendChild(taggaTableBody);
		
		return taggaTable;*/
		
		return taggaLink;
	}
	
	function getValueForParam(paramName, paramsStr) {
	
		var paramsAndValues = paramsStr.split('&');
		var value = '';
		for(var ii = 0; ii < paramsAndValues.length; ii++) {
		
			var indexOfEquals = paramsAndValues[ii].indexOf('=');
			if(indexOfEquals >= 0) {
				
				if(paramsAndValues[ii].substr(0, indexOfEquals) == paramName) {
				
					value =  paramsAndValues[ii].substr(indexOfEquals + 1)
					break;
				}
			}
		}
		
		return value;
	}
	
	
	function showPopup(url, tagId) {
	
		// create the iframe object and append it to the popup window
		var popup_width = 400;
		var popup_height = 420;
		var close_img_width = 18;
		var close_img_height = 18;
		
		// set the position of the close button
		var closeDiv = document.getElementById('close_div');
		closeDiv.style.position = 'absolute';
		closeDiv.style.top = '10px';
		closeDiv.style.left = (popup_width - close_img_width - 10) + 'px';
		
		if(!TaggaBrowser.IE) {
		
			closeDiv.style.display = 'none';
		}
		
		var iframe = document.createElement('iframe');
		iframe.setAttribute('id', 'tagga_iframe');
		iframe.style.border = '0';
		iframe.style.width = popup_width + 'px';
		iframe.style.height = popup_height + 'px';
		iframe.src = url;
		iframe.scrolling = 'no';
		iframe.frameBorder = '0';
		iframe.allowTransparency = 'true';

		if(!TaggaBrowser.IE) {
		
			iframe.setAttribute('onload', 'javascript:showCloseDiv();');
		}
	
		// display the background div
		var backgroundDiv = document.getElementById('tagga_background');
		
		backgroundDiv.style.width = '100%';
		if(document.taggaViewport.getScrollOffsets().left > 0) {
		
			backgroundDiv.style.width = (document.taggaViewport.getScrollOffsets().left + document.taggaViewport.getWidth()) + 'px';
		}
		
		backgroundDiv.style.height = '100%';
		if(document.taggaViewport.getScrollOffsets().top > 0) {
		
			backgroundDiv.style.height = (document.taggaViewport.getScrollOffsets().top + document.taggaViewport.getHeight()) + 'px';
		}
		
		backgroundDiv.style.display = 'block';

		var popupPositionLeft = popup_width/2;
		var popupPositionTop = popup_height/2;
		
		if (typeof window.innerWidth != 'undefined') {

			var linkLeft = window.innerWidth/2 - popupPositionLeft;
			var linkTop = window.innerHeight/2 - popupPositionTop;
		
		} else {
			
			var linkLeft = document.documentElement.clientWidth/2 - popupPositionLeft;
			var linkTop =document.documentElement.clientHeight/2 - popupPositionTop;
			
		}
		/*
		
		// figure out where to open the window
		var taggaLink = document.getElementById(tagId);
	
		var linkLeft = _taggaCumulativeOffset(taggaLink).left;
		var linkTop =  _taggaCumulativeOffset(taggaLink).top + taggaLink.offsetHeight;
		
		// make sure the window hasn't moved off the bottom or right side
		var windowRight = popup_width + linkLeft;
		var windowBottom = popup_height + linkTop;
		
		// move the popup so that it is within the viewable area
		var windowExtends = document.taggaViewport.getWidth() + document.taggaViewport.getScrollOffsets().left - windowRight - 10;
		if(document.taggaViewport.getWidth() > popup_width && windowExtends < 0) {
		
			linkLeft += windowExtends;
		}
		
		windowExtends = document.taggaViewport.getHeight() + document.taggaViewport.getScrollOffsets().top - windowBottom;
		if(document.taggaViewport.getHeight() > popup_height && windowExtends < 0) {
		
			// make the bottom of it touch the top of the link in this case
			linkTop = _taggaCumulativeOffset(taggaLink).top - (popup_height/2);
		} */
		
		
		// add the iframe
		var taggaPopup = document.getElementById('tagga_popup');
		taggaPopup.appendChild(iframe);
		
		// set the styles
		taggaPopup.style.position = 'fixed';
		taggaPopup.style.top = linkTop + 'px';
		//taggaPopup.style.left = linkLeft + 'px';
		taggaPopup.style.left = '-200px';
		taggaPopup.style.margin = '0 0 0 50%';
		taggaPopup.style.display = 'block';
		
		/*taggaPopup.style.display = 'block';
		taggaPopup.style.position = 'absolute';
		taggaPopup.style.top = linkTop + 'px';
		taggaPopup.style.left = linkLeft + 'px';*/
	}
	
	function showCloseDiv() {
	
		document.getElementById('close_div').style.display = 'block';
	}
	
	function hidePopup() {
		
		// hide the windows
		var taggaPopup = document.getElementById('tagga_popup');
		taggaPopup.style.display = 'none';
		document.getElementById('tagga_background').style.display = 'none';
		
		// remove the iframe element
		var iframe = document.getElementById('tagga_iframe');
		if(iframe != null) {
			
			taggaPopup.removeChild(iframe);
		}
	}
	
	function extractJsParams() {
		
		// get the base URL of this script so that we can build the server URLs later on
		// also search for and get any input parameters
		var scriptParams = '';
		var thisScript = 'js/partnerswebtoolkit.js';
		var scriptTags = document.getElementsByTagName('script');
		for(var ii = 0; ii < scriptTags.length; ii++) {
		
			if(scriptTags[ii].getAttribute('src') != null && 
				scriptTags[ii].getAttribute('src').length > 0) {
			
				// find this script in order to extract the base URL
				var foundIndex = scriptTags[ii].getAttribute('src').search(thisScript);
				if(foundIndex > 0) {
					
					taggaScriptUrl = scriptTags[ii].getAttribute('src').substr(0, foundIndex);
					
					// extract any parameters appended on the JS script
					scriptParams = scriptTags[ii].getAttribute('src').substr(foundIndex + thisScript.length);
					if(scriptParams.length > 0 && scriptParams.charAt(0) == '?') {
					
						taggaKey = getValueForParam('key', scriptParams.substr(1));
					}
					
					// we found our script, so stop searching the others
					break;
				}
			}
		}
	}
	
	function createPopupDiv() {
		
		// add the popup to the body
		var popupWindow = document.createElement('div');
		popupWindow.setAttribute('id', 'tagga_popup');
		popupWindow.style.display = 'none';
		
		// create the close button
		var closeDiv = document.createElement('div');
		closeDiv.setAttribute('id', 'close_div');
		
		// create the close image
		var closeImage = document.createElement('img');
		//closeImage.setAttribute('src', taggaScriptUrl + 'img/closelabel-transparent.gif');
		closeImage.setAttribute('src', taggaScriptUrl + 'img/popup/close-popup.png');
		closeImage.setAttribute('title', 'Close');
		closeImage.style.border = 0;
		
		// create the close link
		var closeLink = document.createElement('a');
		closeLink.style.cursor = 'pointer';
		closeLink.setAttribute('href', 'javascript:hidePopup();');
		closeLink.appendChild(closeImage);
		
		closeDiv.appendChild(closeLink);
		
		// attach the close div to the upper right section of the popupWindow
		popupWindow.appendChild(closeDiv);
	
		// attache the whole thing to the body	
		document.body.appendChild(popupWindow);
		
		// create the opaque background div
		var backgroundDiv = document.createElement('div');
		backgroundDiv.style.cursor = 'default';
		backgroundDiv.setAttribute('id', 'tagga_background');
		backgroundDiv.style.display = 'none';
		
		// put the background div in as a link so IE7 can close it
		var backgroundDivCloseLink = document.createElement('a');
		backgroundDivCloseLink.style.cursor = 'default';
		backgroundDivCloseLink.setAttribute('href', 'javascript:hidePopup();');
		backgroundDivCloseLink.appendChild(backgroundDiv);
		
		// add the background to the body
		document.body.appendChild(backgroundDivCloseLink);
	}
	
	function createTaggaUrl(tagg, customContent, key, jsonDataStr, encoding) {
	
		// process the variables or find the rss feeds on the page
		var taggaLink = taggaScriptUrl + 'partners/sendtomobile?';
		if(tagg.length > 0) {
		
			// this means we are subscribing to a specific feed
			taggaLink += 'tagg=' + tagg;
		} else if(customContent.length > 0) {
			//remove html tags
			var re = /(<([^>]+)>)/gi;
			customContent = customContent.replace(re, "");
			customContent = customContent.replace("&nbsp;"," ");
		
			// this means we are just sending this message straight to mobile
			taggaLink += 'content=' + encodeURIComponent(escape(customContent));
			
		} else if(jsonDataStr.length > 0) {
		
			taggaLink += 'jsonData=' + jsonDataStr;
		} else { 
		
			// find the RSS feed
			var rssLinks = new Array();
			var linkTags = document.getElementsByTagName('link');
			for(var ii = 0; ii < linkTags.length; ii++) {
					
				// check if the link is a feed
				if(linkTags[ii].getAttribute('type') != null && 
					(linkTags[ii].getAttribute('type') == 'application/rss+xml' || 
						linkTags[ii].getAttribute('type') == 'application/rss+atom')) {
					
					// store it's hyperlink
					if(linkTags[ii].getAttribute('href') != null && 
						linkTags[ii].getAttribute('href').length > 0) {
						
						rssLinks.push(linkTags[ii].getAttribute('href'));
					}
				}
			}
			
			// process the found rss links
			if(rssLinks.length > 0) {
			
				// just take the first one found on the page
				taggaLink += 'feedUrl=' + rssLinks[0];
			}
		}
		
		// if a publisher key was provided add it to the link so that we can track it
		if(key.length > 0) {
		
			taggaLink += '&key=' + key;
		}
		
		// if the encoding was found, add it to the link
		if(encoding.length > 0) {
		
			taggaLink += '&encoding=' + encoding;
		}
		
		return taggaLink;
	}
	
	function processTaggaDataDiv(taggaDataDiv) {
	
		var taggaReturnData = new Object();
		taggaReturnData.paid = 'false';
	
		var numNodes = taggaDataDiv.childNodes.length;
		for(var ii = 0; ii < numNodes; ii++) {
		
			// process all the divs
			if(taggaDataDiv.childNodes[ii].nodeName == 'DIV') {
			
				var divName = taggaDataDiv.childNodes[ii].getAttribute('name');
				
				// remove any apostraphes or double quotes...
				var divValue = taggaDataDiv.childNodes[ii].innerHTML.replace(/'/g, "").replace(/"/g, "");
				
				if(divName != null) {
				
					switch(divName) {
					
						case 'tagga_data_tagg':
							if(divValue == null || divValue.match(/^[a-z0-9]{4,10}$/i) == null) {
								
								alert(divName + ' must be an alphanumeric string no smaller than 4 characters and no larger than 10 characters.');
								return;
							}
							taggaReturnData.tagg = divValue;
							break;
						case 'tagga_data_title':
							if(divValue == null || divValue.length <= 0) {
								
								alert(divName + ' cannont be empty.');
								return;
							}
							taggaReturnData.title = divValue.substr(0, 255);
							break;
						case 'tagga_data_message':
							if(divValue == null || divValue.length <= 0) {
								
								alert(divName + ' cannont be empty.');
								return;
							}
							taggaReturnData.message = divValue;
							break;
						case 'tagga_data_url':
							taggaReturnData.url = divValue.substr(0, 255);
							break;
						case 'tagga_data_logo':
							taggaReturnData.logo = divValue.substr(0, 255);
							break;
						case 'tagga_data_map_address':
							taggaReturnData.mapAddress = divValue.substr(0, 255);
							break;
						case 'tagga_data_paid':
							taggaReturnData.paid = divValue.substr(0, 10);
							break;
						case 'tagga_data_daily_budget':
							if(divValue.match(/^[0-9]+$/) == null) {
							
								alert(divName + ' must be an integer number (no decimal point or cents!)');
								return;
							}
							
							if(divValue < 5) {
							
								alert(divName + ' must be 5 or greater');
								return;
							}
							
							taggaReturnData.dailyBudget = divValue.substr(0, 8);
							break;
						case 'tagga_data_detailed_info':
							taggaReturnData.detailedInfo = divValue.substr(0, 1023);
							break;
						case 'tagga_data_keywords':
							taggaReturnData.keywords = divValue.substr(0, 255);
							break;
						case 'tagga_data_images':
							if(divValue != null) {
								
								taggaReturnData.images = processTaggaDataImages(taggaDataDiv.childNodes[ii]);
							}
							break;
						case 'tagga_data_direct_url':
							taggaReturnData.directUrl = divValue.substr(0, 10);
							break;
						default:
							break;
					}
				}
			}
		}
		
		// cut down the message length depending on the campaign type
		if(taggaReturnData.paid == 'true') {
		
			taggaReturnData.message = taggaReturnData.message.substr(0, 110);
		} else {
		
			taggaReturnData.message = taggaReturnData.message.substr(0, 110);
		}
		
		// convert it to a JSON string and return it
		return JSON.stringify(taggaReturnData);
	}
	
	function processTaggaDataImages(taggaImagesDiv) {
		
		var taggaReturnData = new Array();
	
		// limit the number of images...otherwise URL may be too long
		var imageCounter = 0;
		var numNodes = taggaImagesDiv.childNodes.length;
		for(var ii = 0; ii < numNodes; ii++) {
		
			if(taggaImagesDiv.childNodes[ii].nodeName == 'DIV') {
			
				var divName = taggaImagesDiv.childNodes[ii].getAttribute('name');
				var divValue = taggaImagesDiv.childNodes[ii].innerHTML;

				if(divName != null && divName == 'tagga_data_image_url') {
				
					taggaReturnData.push(divValue.substr(0, 255));
					imageCounter++;
				}
				
				if(imageCounter >= 5) {
				
					break;
				}
			}
		}
		
		return taggaReturnData;
	}
	
	function addLoadEvent(func) {
	
		var oldonload = window.onload;
		if(typeof window.onload != 'function') {
			
			window.onload = func;
		} else {
			
			window.onload = function() {
			
				if(oldonload) {
				
					oldonload();
				}
				
				func();
			}
		}
	}
	
	// register our onload function
	addLoadEvent(taggaOnLoad);
}
