// Shortcut to grab elements by id
function $(id){
	if(document.getElementById(id)){
		return document.getElementById(id);
	}
	return null;
}

function readCookie(){
	return 1;
}

function popupInit(){
	var browser=getBrowserInfo();
	// Create the div
	var popup=document.createElement('DIV');
	popup.id="ccpup";
	// Create the contents
	var popupTitleContainer=document.createElement('DIV');
	popupTitleContainer.id="ccpupttl";
	var popupTitle=document.createElement('H3');
	var closeImg=document.createElement('IMG');
	closeImg.id="ccpupclose";
	closeImg.src="/images/closex.gif";
	var popupBody=document.createElement('DIV');
	popupBody.id="ccpupbd";
	
	
	popupTitle.appendChild(closeImg);
	titleContent=document.createTextNode('Send to Friends');
	popupTitle.appendChild(titleContent);
	popupTitleContainer.appendChild(popupTitle);
	popup.appendChild(popupTitleContainer);
	popup.appendChild(popupBody);

	// Append the popup to the document
	document.body.appendChild(popup);

	// Provide appropriate border handling for ie
	if(browser.name=='msie' && browser.version>=5.5){
		var popupFooterContainer=document.createElement('DIV');
		popupFooterContainer.id="ccpupftr";
		$('ccpupbd').style.paddingBottom=0;
		popupTitle.style.width="231px";
		popup.appendChild(popupFooterContainer);
	}

	// browser-specific transparency fixes for IE
	if(browser.name=='msie' && browser.version>=5.5){
		$('ccpupttl').style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/ccpup_top.png', sizingMethod='crop')";
		$('ccpupbd').style.height="100px";
		//$('ccpup').style.position="static";
		$('ccpupbd').style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/ccpup_btm.png', sizingMethod='crop')";
		$('ccpupftr').style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/ccpup_ftr.png', sizingMethod='crop')";
	}
	else{
		$('ccpupttl').style.background="transparent url(/images/ccpup_top.png) no-repeat top left";
		$('ccpupbd').style.background="transparent url(/images/ccpup_btm.png) no-repeat bottom left";
	}
}


function openPopup(cid){
	// Create the popup if this is the first time clicking on it
	if(!$('ccpup')){
		popupInit();
	}	

	// Clear the ccpupbd contents by removing all children
	clearDiv('ccpupbd');
	
	var popupForm=document.createElement('FORM');
	var to=document.createElement('DIV');
	to.className="ccpupfrmfld";
	to.appendChild(document.createTextNode('To: '));
	var from=document.createElement('DIV');
	from.className="ccpupfrmfld";
	from.appendChild(document.createTextNode('From: '));
	var textarea=document.createElement('TEXTAREA');
	textarea.id="ccpupto";
	textarea.style.wordWrap="normal";
	var tonote=document.createElement('DIV');
	tonote.id="ccpuptonote";
	tonote.className="ccpupfrmnt";
	tonote.appendChild(document.createTextNode('Enter as many emails as you like, one per line.'));
	var cidinput=document.createElement('INPUT');
	cidinput.id="ccpupcid";
	cidinput.value=cid;
	cidinput.setAttribute("type","hidden");
	var frominput=document.createElement('INPUT');
	frominput.id="ccpupfrm";
	frominput.setAttribute("type","text");
	var fromnote=document.createElement('DIV');
	fromnote.id="ccpupfrmnote";
	fromnote.className="ccpupfrmnt";
	fromnote.appendChild(document.createTextNode('Your name or email'));
	var description=document.createElement('P');
	description.id="ccpupmessage";
	var str="An email will be sent to the address(es) you enter, with a description of this deal and an easy link to allow your friends to take advantage of this great offer."
	description.appendChild(document.createTextNode(str));
	var submit=document.createElement('INPUT');
	submit.id="ccpupfrmbtn";
	submit.setAttribute("type","button");
	submit.setAttribute("value","Send");
	popupForm.appendChild(submit);
	var progress=document.createElement('IMG');
	progress.id="puppgrs";
	progress.src="/images/progress.gif";
	progress.style.visibility="hidden";
	
	// Add the to: section
	popupForm.appendChild(to);
	popupForm.appendChild(textarea);
	popupForm.appendChild(tonote);
	// Add the from: section
	popupForm.appendChild(from);
	popupForm.appendChild(frominput);
	popupForm.appendChild(fromnote);
	popupForm.appendChild(submit);
	popupForm.appendChild(progress);
	popupForm.appendChild(cidinput);
	// Add the bottom note
	popupForm.appendChild(description);
	// Append the form
	$('ccpupbd').appendChild(popupForm);

	// Add the events to submit and close
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		$('ccpupclose').addEventListener('click',closeccpup,false);
		submit.addEventListener('click',sendFriendEmails,false);
	} else { // IE
		$('ccpupclose').attachEvent('onclick',closeccpup);
		submit.attachEvent('onclick',sendFriendEmails);
	}


	// Find the coordination to show the popup
	var ele=$('friend'+cid);
	var left=0;
	var top=0;
	while(ele){
		left+=ele.offsetLeft;
		top+=ele.offsetTop;
		ele=ele.offsetParent;
	}
	
	// Make the popup visible
	$('ccpup').style.display="block";
	$('ccpup').style.position="absolute";
	$('ccpup').style.top=(top+13)+"px";
	$('ccpup').style.left=(left-91)+"px";

	if(readCookie("user_id")){
		getEmail();
	}

	return false;
}

function sendFriendEmails(){
	// Get the form data
	postData='f='+encodeURIComponent($('ccpupfrm').value)+'&t='+encodeURIComponent($('ccpupto').value)+'&c='+$('ccpupcid').value;

	// Disable the input elements
	var inputs=$('ccpupbd').getElementsByTagName('input');
	for(j=0;j<inputs.length;j++){
		inputs[j].disabled=true;
	}
	var inputs=$('ccpupbd').getElementsByTagName('textarea');
	for(j=0;j<inputs.length;j++){
		inputs[j].disabled=true;
	}
	$('puppgrs').style.visibility="visible";

	var xhReq=createXMLHttpRequest();
	xhReq.open("post","/em/friend.phtml",true);
	xhReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhReq.onreadystatechange=function(){
		if(xhReq.readyState!=4){return;}
		$('puppgrs').style.visibility="hidden";
		var xml=xhReq.responseXML;
		updatePopup(xml);
	};
	xhReq.send(postData);
}

function closeccpup()
{
	if($('ccpup')){
		$('ccpup').style.display = "none";
	}
	return false;
}

function getEmail(){
        var xhReq=createXMLHttpRequest();
        xhReq.open("get","/em/cid_em.phtml",true);
        xhReq.onreadystatechange=function(){
                if(xhReq.readyState!=4){return;}
                var em=xhReq.responseText;
		if(em!='none'){
        		$("ccpupfrm").value=em;
		}
	};
        xhReq.send(null);
}

function updatePopup(xml){
	var defaultToNote="Enter as many emails as you like, one per line.";
	var defaultFromNote="Your name or email";
	var defaultMessage="An email will be sent to the address(es) you enter, with a description of this deal and an easy link to allow your friends to take advantage of this great offer.";
	var status=xml.getElementsByTagName("status")[0].firstChild.nodeValue;
	var msg=xml.getElementsByTagName("message")[0].firstChild.nodeValue;

	// Clear the previous messages and notes (and return them to default values);
	clearDiv("ccpupmessage");
	$('ccpupmessage').appendChild(document.createTextNode(defaultMessage));
	clearDiv("ccpuptonote");
	$('ccpuptonote').appendChild(document.createTextNode(defaultToNote));
	$('ccpuptonote').style.color="#AAA";
	clearDiv("ccpupfrmnote");
	$('ccpupfrmnote').appendChild(document.createTextNode(defaultFromNote));
	$('ccpupfrmnote').style.color="#AAA";

	// Get the new message
        if(xml.getElementsByTagName("message")[0]){
                var newMessage=xml.getElementsByTagName("message")[0].firstChild.nodeValue;
		clearDiv("ccpupmessage");
		$('ccpupmessage').appendChild(document.createTextNode(newMessage));
        }
        if(xml.getElementsByTagName("status")[0]){
                var status=xml.getElementsByTagName("status")[0].firstChild.nodeValue;
        	if(status=='success'){
			$('ccpupmessage').style.color="green";
			closeLink=document.createElement('A');
			closeLink.appendChild(document.createTextNode('close popup'));
			closeLink.href="#";
	        	// Add the events to and close
	        	if(window.addEventListener){ // Mozilla, Netscape, Firefox
	        	        closeLink.addEventListener('click',closeccpup,false);
        		} else { // IE
        		        closeLink.attachEvent('onclick',closeccpup);
        		}

			$('ccpupmessage').appendChild(closeLink);
			// Close the window automatically for success
			setTimeout('closeccpup()',2000);
		}
	}


	// See if there were errors
	if(xml.getElementsByTagName("errors")[0]){
		var errorArray=xml.getElementsByTagName("errors")[0].childNodes;
	}
	for(i=0;i<errorArray.length;i++){
		error=errorArray[i];
		errorField=error.getElementsByTagName("field")[0].firstChild.nodeValue;
		fieldValue=((error.getElementsByTagName("value")[0].firstChild)?error.getElementsByTagName("value")[0].firstChild.nodeValue:'');
		errorMessage=error.getElementsByTagName("errormsg")[0].firstChild.nodeValue;
		clearDiv(errorField+"note");
		errormsg=document.createElement("SPAN");
		errormsg.className="ccpuperr";
		errormsg.appendChild(document.createTextNode(errorMessage));
		$(errorField+"note").appendChild(errormsg);
		$(errorField).value=fieldValue;
		$(errorField).disabled=false;
		$('ccpupfrmbtn').disabled=false;
	}
}

function createXMLHttpRequest(){
	try {return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}
	try {return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}
	try {return new XMLHttpRequest();}catch(e){}
	alert("XMLHttpRequest not supported");
	return null;
}

function clearDiv(parent)
{
	var kids=$(parent).childNodes;
	for(j=0;j<kids.length;j++){
		$(parent).removeChild(kids[j]);
	}
}

function getBrowserInfo()
{
	browser=new Object();
	browser.name=browser.version=browser.os="unknown";
	var userAgent=navigator.userAgent.toLowerCase();
	var browserListArray=new Array("firefox", "msie", "netscape", "opera", "safari");
	var osListArray=new Array("linux", "mac", "windows", "x11");
	for(var i=0,n=browserListArray.length;i<n;i++){
		// get browser name and version
		var strPosition=userAgent.indexOf(browserListArray[i])+1;
		if(strPosition>0){
			browser.name=browserListArray[i]; // browser name

			var versionPosition = strPosition + browser.name.length;
			var incr=((browser.name=="safari")||(userAgent.charAt(versionPosition+4)>0&&userAgent.charAt(versionPosition+4)<9))?5:3;

			browser.version=userAgent.substring(versionPosition,versionPosition+incr); // browser version
		}
	}
	for(var i=0,n=osListArray.length;i<n;i++){
		var strPosition = userAgent.indexOf(osListArray[i])+1;
		if(strPosition>0){
			browser.os=osListArray[i];
		}
	}
	return browser;
}

// Moves the box object to be directly beneath an object.

function move_box(an, box)
{
    var cleft = 0;
    var ctop = 0;
    var obj = an;

    while (obj.offsetParent)
    {
        cleft += obj.offsetLeft;
        ctop += obj.offsetTop;
        obj = obj.offsetParent;
    }

    box.style.left = cleft + 'px';

    ctop += an.offsetHeight + 8;

    // Handle Internet Explorer body margins,
    // which affect normal document, but not
    // absolute-positioned stuff.
    if (document.body.currentStyle &&
        document.body.currentStyle['marginTop'])
    {
        ctop += parseInt(
            document.body.currentStyle['marginTop']);
    }

    box.style.top = ctop + 'px';
}

function addbarelink(pmURL, pmLinkName)
{
  var vAncLink  =       document.createElement('A');
  vAncLink.href =       pmURL;
  vAncLink.setAttribute('id', 'closeLink');
  vAncLink.setAttribute( 'accesskey', '1' );
  var vText     =       document.createTextNode(pmLinkName);
  vAncLink.appendChild(vText);
  return vAncLink;
}

function addImageLink(pmURL, pmImagePath)
{
  var InnerDiv = document.createElement('DIV');
  InnerDiv.setAttribute('id', 'ccpupfrmfld');
  InnerDiv.setAttribute('style', 'position:absolute;padding:0;cursor: pointer;cursor: hand;');

  var vAncLink  =       document.createElement('A');
  vAncLink.name =       'yahImage';
  vAncLink.href =       pmURL;
  var ImgTag    =       document.createElement('IMG');
  ImgTag.src    =       pmImagePath;
  ImgTag.setAttribute('border', '0');
  vAncLink.appendChild(ImgTag);

  InnerDiv.appendChild(vAncLink);

  return InnerDiv;
}

// Shows a box if it wasn't shown yet or is hidden
// or hides it if it is currently shown
function show_hide_box(an, width, height, borderStyle,pmoptn)
{
    var href    =       an.href;

        var obj = an;
        if (obj.offsetParent) {
                curleft = obj.offsetLeft
                curtop = obj.offsetTop
                while (obj = obj.offsetParent) {
                        curleft += obj.offsetLeft
                        curtop += obj.offsetTop
                }
        }


        var browser = getBrowserInfo();
    var boxdiv  =       document.getElementById(href);
        var innerDiv    =       document.getElementById("innerDiv");

    if (boxdiv != null || innerDiv != null)
    {
        if (boxdiv.style.display == 'none')
        {
            move_box(an, boxdiv);
                        move_box(an, innerDiv);
            boxdiv.style.display='block';
                        innerDiv.style.display='block';
            bringToFront(boxdiv);
                        bringToFront(innerDiv);
                        innerDiv.style.position         = 'absolute';
                        innerDiv.style.top                      = curtop+20;
                        innerDiv.style.left                     =  curleft+15;

        } else {
            boxdiv.style.display ='none';
                        innerDiv.style.display = "none";
                        move_box(an, boxdiv);
                        move_box(an, innerDiv);
            boxdiv.style.display        =       'block';
                        innerDiv.style.display  =       'block';
                    bringToFront(boxdiv);
                        bringToFront(innerDiv);
                        innerDiv.style.position         = 'absolute';
                        innerDiv.style.top                      =  curtop+20;
                        innerDiv.style.left                     =  curleft+15;
                }
        return false;
    }



    // Create box object through DOM
    var boxdiv = document.createElement('DIV');
    // Assign id equalling to the document it will show
    boxdiv.setAttribute('id', href);


        var innerDiv = document.createElement('DIV');
        boxDivLeft = boxdiv.offsetLeft ;

        innerDiv.style.display = "block";
        innerDiv.setAttribute('id', 'innerDiv');
        innerDiv.style.position         = 'absolute';
        innerDiv.style.top                      = curtop + 20 + 'px';
        innerDiv.style.left                     = curleft + 15  + 'px';
        boxdiv.style.position   = 'absolute';
        boxdiv.style.width              = width + 'px';
        boxdiv.style.height     = height + 'px';
        innerDiv.style.zIndex   = '10';
        innerDiv.innerHTML = '<table width="340" align="left" border="0" style="margin-left:3px;margin-top:20px" cellpadding=0 cellspacing=0><tr><td nowrap><span class="st4">Subscribe to '+m_name+' Coupons</span></td><td width="71" align="right" valign="top"><span class="st7"><a href="javascript:fnClose(\''+href+'\')" class="st7">close</a></span></td></tr><tr><td colspan="2"><span class="st9">Choose your favorite RSS reader below:</span></td></tr><tr><td colspan="2" align="center"><table width="100%" align="center" cellpadding="0" cellspacing="3"><tr><td width="32%" align="left"><a href="http://add.myst.yahoo.com/content?url=http://www.Coupons.com/RSS/target.xml&lg=ig"><img src="/images/yahooRss.gif" width="91" height="17" border="0" /></a></td><td width="26%" align="left"><a href="http://feeds.myst.aol.com/?url=http://www.Coupons.com/RSS/target.xml"><img src="/images/aolRss.gif" border="0"/></a></td><td width="42%" align="left"><a href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http://www.Coupons.com/RSS/target.xml"><img src="/images/gator.gif" width="91" height="17" border="0" /></a></td></tr><tr><td align="left"><a href="http://www.rojo.com/add-subscription?resource=http://www.Coupons.com/RSS/target.xml"><img src="/images/rojoRss.gif" width="91" height="17" border="0" /></a></td><td align="left"><a href="http://myst.msn.com/addtomystmsn.armx?id=rss&ut=http://www.Coupons.com/RSS/target.xml"><img src="/images/msnRss.gif" width="71" border="0" height="14" /></a></td><td align="left"><a href="http://www.bloglines.com/sub/http://www.Coupons.com/RSS/target.xml"><img src="/images/bloglinesRss.gif" width="76" height="17" border="0" /></a></td></tr><tr><td align="left" colspan="3"><table align="left" width="100%"><tr><td width="38%" align="left"><a href="http://fusion.google.com/add?feedurl=http://www.Coupons.com/RSS/target.xml"><img src="/images/googleRss.gif" border="0" width="104" height="17" /></a></td><td width="62%" align="left"><a href="http://www.pageflakes.com/subscribe.aspx?url=http://www.Coupons.com/RSS/target.xml"><img src="/images/pageflakesRss.gif" width="116" height="17" border="0" /></a></td></tr></table></td></tr></table></td></tr><tr><td colspan="2" class="st9">Paste this link into your favorite RSS desktop reader:</td></tr><tr><td colspan="2" ><table width="99%"  align="center"  bgcolor="#FFFFCC" border="1" bordercolor="#666666"><tr><td bordercolor="#FFFFCC" bordercolordark="#FFFFCC"><span class="st11">http://www.Coupons.com/RSS/target.xml</span></td></tr></table><hr color="#666666" width="99%" size="1"/></td></tr><tr><td colspan="2" class="st9">See all RSS Coupons coupons:</td></tr><tr><td colspan="2"><a href="http://www.Coupons.com/RSS/rss.xml" class="st12">http://www.Coupons.com/RSS/rss.xml</a></td></tr></table>';




        // browser-specific transparency fixes for IE

        if( browser.name=='msie' && browser.version >= 5.5 ){
                boxdiv.style.filter     =       'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/images/rss_popup_bg.png\', sizingMethod=\'crop\');';
        } else {
                boxdiv.style.background =   'transparent url(/images/rss_popup_bg.png) no-repeat left top';
        }

        document.body.appendChild(innerDiv);
    document.body.appendChild(boxdiv);
        bringToFront(innerDiv);

        var offset = 0;
    move_box(an, boxdiv);



    // The script has successfully shown the box,
    // prevent hyperlink navigation.
    return false;
}


function closeCBoxPopup()
{
        if($('boxdiv')){
                $('boxdiv').style.display = "none";
                $('innerDiv').style.display = "none";
        }
        return false;
}


function getAbsoluteDivs()
{
    var arr = new Array();
    var all_divs = document.body.getElementsByTagName("DIV");
    var j = 0;

    for (i = 0; i < all_divs.length; i++)
        if (all_divs.item(i).style.position=='absolute')
        {
            arr[j] = all_divs.item(i);
            j++;
        }

    return arr;
}

function bringToFront(obj)
{
    if (!document.getElementsByTagName)
        return;

    var divs = getAbsoluteDivs();
    var max_index = 0;
    var cur_index;

    // Compute the maximal z-index of
    // other absolute-positioned divs
    for (i = 0; i < divs.length; i++)
    {
        var item = divs[i];
        if (item == obj ||
            item.style.zIndex == '')
            continue;

        cur_index = parseInt(item.style.zIndex);
        if (max_index < cur_index)
        {
            max_index = cur_index;
        }
    }

    obj.style.zIndex = max_index + 1;
}

function fnClose(divID)
{
        document.getElementById(divID).style.display ="none";
        document.getElementById("innerDiv").style.display ="none";
}


