/* -*- Mode: JavaScript; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
YAHOO.namespace('vs');

function gebi(i){return document.getElementById(i);}
function clog(txt){if(window.console){console.log(txt);}}

(function() {
    var Y = YAHOO;
    var YUI = YAHOO.util;
    var VS = YAHOO.vs;

    VS.randDealValues = function (username) {
        var d = new Date();
        var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
        var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
        var daydate = weekday[d.getDay()] + ', ' + monthname[d.getMonth()]+ ' ' + d.getDate();
        var datetime = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
        
        var prod_title = username+"'s Deal on " + daydate +' '+ datetime;
        var review_summary = "Good deal for a " + weekday[d.getDay()]+'!';
        var review = "I, "+username+" can say that this is the greatest deal I have found since the creation of ValueScouts. So today, "+daydate+" must be the greatest day in the history of ValueWeekly! The time right now is: "+datetime;
        var pctoff=Math.floor(Math.random()*101);
        var bigrand=Math.floor(Math.random()*100000001);
        var deal_info = "Awesome deal, "+pctoff+'% off everything!';
        var link = 'http://www.yahoo.com/?rnd='+d.getMonth()+d.getDate()+bigrand;
        var expiry_date = '12/31/2009';
        var purchase_site_name = "DealChimp";
        
        var id_categories = document.getElementById('id_categories');
        if (id_categories) {
            id_categories.options[0].selected =true;
        }
        
        var id_product_title = document.getElementById('id_product_title');
        if (id_product_title) {
            id_product_title.value=prod_title;
        }
        
        var id_review_summary = document.getElementById('id_review_summary');
        if (id_review_summary) {
            id_review_summary.value = review_summary;
        }
        
        var id_review = document.getElementById('id_review');
        if (id_review) {
            id_review.value = review;
        }
        
        var id_deal_info = document.getElementById('id_deal_info');
        if (id_deal_info) {
            id_deal_info.value = deal_info;
        }
        
        var id_link = document.getElementById('id_link');
        if (id_link) {
            id_link.value = link;
        }
        
        var id_expiry_date = document.getElementById('id_expiry_date');
        if (id_expiry_date) {
            id_expiry_date.value = expiry_date;
        }
        
        var id_purchase_site_name = document.getElementById('id_purchase_site_name');
        if (id_purchase_site_name) {
            id_purchase_site_name.value = purchase_site_name;
        }
        
        return false;
        
    };
    
    VS.clickDeal = function(e,obj) {
        YUI.Dom.setStyle('dialog1', 'display', 'block');
        
        var alreadysubscribed = document.getElementById('alreadysubscribed');
        if (alreadysubscribed && alreadysubscribed.value=='no') {
            if (obj) {
                VS.togoLink = obj.togolink;
                if (VS.notRendered) {
                    VS.dialog1.render();
                    VS.notRendered = false;
                }
                VS.dialog1.show();
                var togoLinkEl = document.getElementById('togoLink');
                if (togoLinkEl) {
                    togoLinkEl.value = VS.togoLink;
                }
                
                // if (VS.togoLink != '') {
                //     pageTracker._trackPageview('/_track/interstitial_shown');
                // }
            }
            
            try {
                YUI.Event.preventDefault(e);
            } catch (err) {
                
            }
        }
    };
    
    VS.onDealTextChange = function (e,obj) {
        // debugger;
        if (obj && obj.elid) {
            var el = document.getElementById(obj.elid);
            if (el) {
                if (e.currentTarget) {
                    el.innerHTML = e.currentTarget.value;
                } else if (e.srcElement && e.srcElement.id) {
                    var currEl = document.getElementById(e.srcElement.id);
                    if (currEl) {
                        el.innerHTML = currEl.value;
                    }
                }
            }
        }
    };
    
    VS.init = function() {

        // Define various event handlers for Dialog
        var handleSubmit = function() {
            this.submit();
        };
        var handleCancel = function() {
            this.cancel();
            if (VS.togoLink != '') {
                window.location = VS.togoLink;
            }
        };
        var handleSuccess = function(o) {
            // alert('success!');
            var alreadysubscribed = document.getElementById('alreadysubscribed');
            if (alreadysubscribed) {
                alreadysubscribed.value='yes';
            }
            
            // url to deal is sent in response
            var response = o.responseText;
            if (response != 'false') {
                window.location = response;
            } else {
                var suberror = document.getElementById('suberror');
                if (suberror) {
                    suberror.innerHTML = "There seems to be an error in your email. Please fix and resubmit!";
                }
                VS.dialog1.show();
            }
            // console.log(response);
            // response = response.split("<!")[0];
            // document.getElementById("resp").innerHTML = response;
        };
        var handleFailure = function(o) {
            alert("Submission failed: " + o.status);
        };

        // Instantiate the Dialog
        
        if (VS.newInter) {
            VS.dialog1 = new YAHOO.widget.Dialog("dialog1", 
                                    { width : "640px",
                                        fixedcenter : true,
                                        close: false, //its false here, but we are manually adding a close button in the template itself
                                        modal: true,
                                        visible : false, 
                                        // postmethod: 'form',
                                        constraintoviewport : true,
                                        buttons : [ /*{ text:"Sign Up & Continue", handler:handleSubmit, isDefault:true }*/ ]
                                    });
        } else {
            VS.dialog1 = new YAHOO.widget.Dialog("dialog1", 
                                    { width : "36em",
                                        fixedcenter : true,
                                        close: false, //its false here, but we are manually adding a close button in the template itself
                                        modal: true,
                                        visible : false, 
                                        // postmethod: 'form',
                                        constraintoviewport : true,
                                        buttons : [ { text:"Sign Up & Continue", handler:handleSubmit, isDefault:true } ]
                                    });
        }
                                // removed { text:"Skip", handler:handleCancel },

        // Validate the entries in the form to require that both first and last name are entered
        VS.dialog1.validate = function() {
            var data = this.getData();
            if (data.firstname == "" || data.lastname == "") {
                alert("Please enter your first and last names.");
                return false;
            } else {
                return true;
            }
        };
        
        
        // Wire up the success and failure handlers
        VS.dialog1.callback = { success: handleSuccess,
                                     failure: handleFailure };

        // Render the Dialog
        // VS.dialog1.render();
        VS.notRendered = true;
        var closeElements = YAHOO.util.Dom.getElementsByClassName('container-close', 'a');
        YAHOO.util.Event.addListener(closeElements, "click", function () {
            if (VS.togoLink != '') {
                setTimeout("window.location = '"+VS.togoLink+"'", 0);
            }
            this.cancel();
        }, VS.dialog1, true);
        
        YAHOO.util.Event.addListener("showtest", "click", VS.dialog1.show, VS.dialog1, true);
        YAHOO.util.Event.addListener("hidetest", "click", VS.dialog1.hide, VS.dialog1, true);
    };

    VS.whenLoad = function () {
        VS.shouldPop = true;
        function testInternalLink(el) {
            return el.href.match(document.location.host);
            // && !el.href.match('/out/')
        }
        var internalLinkEls = YUI.Dom.getElementsBy(testInternalLink, "A");
        YUI.Event.addListener(internalLinkEls, "click", function () { VS.shouldPop=false; });
        // alert('call load');
    };
    
    VS.whenUnload = function () {
        if (VS.shouldPop) {
            if (YAHOO.vs.popUrl) {
                var popurl = YAHOO.vs.popUrl;
            } else {
                var popurl = '/signuppopup';
            }
            
            var popwin = window.open(popurl,'PopWin','toolbar=no,status=no,width=500,height=280,scrollbars');
            popwin.moveTo(140,200);         //change the numbers at the left to adjust the top and left margins of
            
            // to make it pop-under
            // popwin.blur();
            // window.focus();
        }
    };


	VS.read_cookie = function(cookie_name) {
	    var my_cookie=""+document.cookie;
	    var ind=my_cookie.indexOf(cookie_name);
	    if (ind==-1 || cookie_name=="") return ""; 
	    var ind1=my_cookie.indexOf(';',ind);
	    if (ind1==-1) ind1=my_cookie.length; 
	    return unescape(my_cookie.substring(ind+cookie_name.length+1,ind1));
	};
	
	VS.superSetVar = function (appendValue) {
	    var getVar = YAHOO.vs.read_cookie('__utmv');             // read the __utmv cookie
	    hasValue = getVar.indexOf(appendValue);     // does the cookie already have the value we want to append?
	    if ( hasValue == -1 ) {                                     // if the new value is not already in the cookie
	        removePrefix = /^.*\.(.*)/.exec(getVar);    // __utmv cookie has the format 12345678.cookieValue - remove the ## prefix
	        if (removePrefix && removePrefix[1]) {
	            newVar = removePrefix[1] + appendValue; // append the value
	        }else{
	            newVar = appendValue;                                 // this will execute if the cookie was not already set.
	        }
	            var superSetVarTracker = _gat._getTracker("UA-7777742-1");    // set up a tracker to call _setVar from
	            superSetVarTracker._initData();    
	            superSetVarTracker._setVar(newVar);                                     // call _setVar with the new value
	    }
	};
	
	VS.unSetVar = function(removeValue){
	    var getVar = YAHOO.vs.read_cookie('__utmv');                 // read the __utmv cookie
	    hasValue = getVar.indexOf(removeValue);         // does the cookie have the value we want to remove?
	    if ( hasValue != -1 ) {                                         // if the value is in the cookie then . . .    otherwise, there is nothing further to do.
	        removePrefix = /^.*\.(.*)/.exec(getVar);    // __utmv cookie has the format 12345678.cookieValue - remove the ## prefix
	        if (removePrefix && removePrefix[1]) {        // if we remove the prefix then. . .
	            //
	            var re = removeValue + '[^/]*';
	            re = new RegExp(re,'g');
	            newVar = removePrefix[1].replace(re,""); // newVar = removePrefix[1] MINUS removeValue
	            //
	            var superSetVarTracker = _gat._getTracker("UA-7777742-1");    // set up a tracker to call _setVar from
	            superSetVarTracker._initData();    
	            superSetVarTracker._setVar(newVar);                                     // call _setVar with the new value
	        }
	        
	    }
	};

    VS.bookOnlineclickDeal = function (e,obj) {
        YUI.Dom.setStyle('dialog1', 'display', 'block');
        
        if (obj) {
            VS.togoLink = obj.togolink;
            if (VS.notRendered) {
                VS.dialog1.render();
                VS.notRendered = false;
            }
            
            VS.dialog1.show();
            var beaconspan = document.getElementById('beaconspan');
            if (beaconspan) {
                beaconspan.innerHTML = "<img src='http://www.bloomspot.com/la_residence_inter_shown_span.png' width='1' height='1' style='display:block; position: absolute; top:-1000px; left:-1000px;'>";
            }
            var togoLinkEl = document.getElementById('togoLink');
            if (togoLinkEl) {
                togoLinkEl.value = VS.togoLink;
            }
        }
        
        try {
            YUI.Event.preventDefault(e);
        } catch (err) {
            
        }
        
        window.setTimeout(function () {
            VS.bookOnlinehandleSubmit();
        }, 12500);
    };
    
    VS.bookOnlineInfo_init = function () {

        // Define various event handlers for Dialog
        VS.bookOnlinehandleSubmit = function() {
            if (VS.togoLink != '') {
                window.location = VS.togoLink;
            }
        };
        var handleCancel = function() {
            this.cancel();
        };
        var handleSuccess = function(o) {
        };
        var handleFailure = function(o) {
            alert("Submission failed: " + o.status);
        };

        // Instantiate the Dialog
        
        VS.dialog1 = new YAHOO.widget.Dialog("dialog1", 
                                { width : "36em",
                                    fixedcenter : true,
                                    close: false, //its false here, but we are manually adding a close button in the template itself
                                    modal: true,
                                    visible : false, 
                                    // postmethod: 'form',
                                    constraintoviewport : true,
                                    buttons : [ { text:"Continue to Deal &rarr;", handler:VS.bookOnlinehandleSubmit, isDefault:true } ]
                                });
                                // removed { text:"Skip", handler:handleCancel },

        // Validate the entries in the form to require that both first and last name are entered
        VS.dialog1.validate = function() {
        };
        
        
        // Wire up the success and failure handlers
        VS.dialog1.callback = { success: handleSuccess,
                                     failure: handleFailure };

        // Render the Dialog
        // VS.dialog1.render();
        VS.notRendered = true;

        YAHOO.util.Event.addListener("dialog1_close", "click", function () {
            if (VS.togoLink != '') {
                // setTimeout("window.location = '"+VS.togoLink+"'", 0);
            }
            this.cancel();
        }, VS.dialog1, true);
        
    };
    
    VS.overDeal = function (e,obj) {
        var el = VS.getElFromE(e);
        // el.style.background = "url(/media/css/images/gray-button-gradient.gif) repeat-x";
        // YUI.Dom.setStyle(el,'background','url(/media/css/images/gray-button-gradient.gif) repeat-x');
        YUI.Dom.setStyle(el.firstChild,'opacity','1');
        
    };

    VS.outDeal = function (e,obj) {
        var el = VS.getElFromE(e);
        YUI.Dom.setStyle(el.firstChild,'opacity','.85');
        // YUI.Dom.setStyle(el,'background','#eeeeee');
    };

    VS.shareDeal = function (e,obj) {
        var el = VS.getElFromE(e);

        if (!VS.shareDealDialog) {
			var bloomReferral = gebi('bloomReferral');
			YUI.Dom.setStyle(bloomReferral, 'display', 'block');
            VS.shareDealDialog = new YAHOO.widget.Dialog("bloomReferral", 
            { width: "500px",
                fixedcenter: true,
                close: false, //its false here, but we are manually adding a close button in the template itself
                modal: true,
                hideaftersubmit: false,
                effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25},
                constraintoviewport : true
                // buttons : [ { text:"Sign Up & Continue", handler:handleSubmit, isDefault:true } ]
            });
        
            var handleSubmit = function () {
            };
        
            // VS.shareDealDialog.asyncSubmitEvent.subscribe(handleSubmit);
            var handleSuccess = function (o) {
                    var response = o.responseText;
                	if (o.getResponseHeader['Bsresult']) {
                        	bsresult = o.getResponseHeader['Bsresult'].replace(/[\s\r\n]+$/, '');
                	}
                	var referral_body = document.getElementById('referral_body');
            	
                    if (bsresult == 'referral_success') {
                            var dialog_title = document.getElementById('offer_title');
                            if (dialog_title) {
                                    dialog_title.innerHTML = "Thank you for sharing this deal with your friends."
                                    YUI.Dom.setStyle(dialog_title,'textAlign','center');
                                    YUI.Dom.setStyle(dialog_title,'fontSize','20px');
                                    YUI.Dom.setStyle(dialog_title,'padding','15px');
                            }
                        
                            var dialog_subtitle = document.getElementById('dialog_subtitle');
                            if (dialog_subtitle) {
                                    YUI.Dom.setStyle(dialog_subtitle,'display','none');
                            }
                        
                            if (referral_body) {
                                    referral_body.innerHTML = "";
                            }
                            pageTracker._trackPageview('/_track/referral_popup/'+obj.dealslug+'/success/');
                            VS.setTimerToCloseDialog(VS.shareDealDialog,3000);
                    } else if (bsresult == 'referral_fail') {
                        	if (o.getResponseHeader['Bserrors']) {
                                	bserrors = o.getResponseHeader['Bserrors'].replace(/[\s\r\n]+$/, '');
                        	}
                        	if (referral_body) {
                        	        referral_body.innerHTML = "Looks like there was an error!: "+bserrors;
                        	}
                    }
            };
        
            var handleFailure = function () {
            
            };
            VS.shareDealDialog.callback = { success: handleSuccess, failure: handleFailure };
            VS.shareDealDialog.render();
            VS.currentDialog = VS.shareDealDialog;
            VS.refPathDialog.hide();
            
            pageTracker._trackPageview('/_track/referral_popup/'+obj.dealslug+'/');
        } else {
            VS.refPathDialog.hide();
            VS.shareDealDialog.show();
        }
        
        var dealslug = document.getElementById('dealslug');
        if (dealslug && obj.dealslug) {
            dealslug.value = obj.dealslug;
        }

        var dialog_title = document.getElementById('dialog_title');
        if (dialog_title && obj.dealtitle) {
            dialog_title.innerHTML = "Invite your friends to <b>"+obj.dealtitle+"</b>";
        }

        var deal_title = document.getElementById('deal_title');
        if (deal_title && obj.dealtitle) {
            deal_title.innerHTML = obj.dealtitle;
        }

        var dialog_subtitle = document.getElementById('dialog_subtitle');
        if (dialog_subtitle && obj.dealinfo) {
            dialog_subtitle.innerHTML = obj.dealinfo;
            YUI.Dom.setStyle(dialog_subtitle,'display','block');
        }
        
		var dealReferralForm = document.getElementById('dealReferralForm');
		if (dealReferralForm) {
			if (VS.deal_referral_actions[obj.dealslug]) {
				dealReferralForm.action = VS.deal_referral_actions[obj.dealslug];
			}
		}
		
		var dealReferralMessage = document.getElementById('id_message');
		if (dealReferralMessage && obj.deal_r_message && obj.deal_r_message != '') {
			dealReferralMessage.value = obj.deal_r_message;
		}
		
        YUI.Event.addListener('go_back','click',function () {
            VS.shareDealDialog.hide();
            VS.refPathDialog.show();
        });
        YUI.Event.stopPropagation(e);
    };
    
    
    VS.getRespHeaderStripNewLines = function (o,key) {
        if (o.getResponseHeader[key]) {
            	return o.getResponseHeader[key].replace(/[\s\r\n]+$/, '');
    	}
    };
    
    VS.setTimerToCloseDialog = function (panel,timeleft) {
        if (panel && timeleft > 1) {
            window.setTimeout(function () {
                panel.hide();
            }, timeleft);
        }
    };

    VS.onEditionsDropdownChange = function(obj) {
        var selected_index = obj.selectedIndex;
        var selected_slug = obj.options[selected_index].value;
        YAHOO.vs.changeEdition(selected_slug);
    };

    VS.changeEdition = function(edition_slug) {
        window.location.href='/' + edition_slug;
    };
    
    VS.getElFromE = function (e) {
        var el;
        if (e.currentTarget) {
            el = e.currentTarget;
        } else if (e.srcElement && e.srcElement.id) {
            el = document.getElementById(e.srcElement.id);
        }
        return el;
    };
    
    VS.increaseHeight = function (e,obj) {
        var el = VS.getElFromE(e);
        var to = obj.to;
        
        if (to) {
            YUI.Dom.setStyle(el,'height',to);
        }
    };
    
    VS.getTaggedReferralUrl = function(request_host,request_path,share_utm,email) {
        var url = 'http://' + request_host + request_path + share_utm + escape(email).replace('+','%2B');
        return url;
    };
    
    VS.referralInitEmailBoxes = function() {
        var obj;
        VS.eboxes = YUI.Dom.getElementsByClassName('email_tab_box');
        YUI.Event.addListener(VS.eboxes, 'change', VS.referralChangeOtherEmails);

        var id_sender = document.getElementById('id_sender');
        YUI.Dom.batch(VS.eboxes, function (el) {
            VS.email_containers = YUI.Dom.getElementsByClassName('youremailcont');
            if (id_sender && id_sender.value != '') {
                el.value = id_sender.value;
                var url = VS.getTaggedReferralUrl(VS.request_host,VS.request_path,VS.share_utm,el.value);
                simple_bitlyfy(url);
                VS.green_checks = YUI.Dom.getElementsByClassName('green_check');
                YUI.Dom.setStyle(VS.green_checks, 'display', 'inline');
                // YUI.Dom.setStyle(VS.email_containers, 'background', '#ffffff');
            } else {
                var url = VS.getTaggedReferralUrl(VS.request_host,VS.request_path,VS.share_utm,"");
                simple_bitlyfy(url);
                // YUI.Dom.setStyle(VS.email_containers, 'background', '#dddddd');
            }
        });

        // Copy to cliboard technique from to: http://code.google.com/p/zeroclipboard/
        VS.clipme = new ZeroClipboard.Client();
		VS.clipme.setHandCursor(true);
		VS.clipme.addEventListener('mouseOver', function () {
		    VS.clipme.setText(gebi('invite_link').value);
		});
		
		VS.clipme.addEventListener('complete', function () {
            alert("The link was successfully copied to your clipboard!");
		});
		VS.clipme.glue('copylink','copy_container');
    };
    
    VS.referralChangeOtherEmails = function (e,obj) {
        var changed_el = VS.getElFromE(e);
        VS.green_checks = YUI.Dom.getElementsByClassName('green_check');
        VS.email_containers = YUI.Dom.getElementsByClassName('youremailcont');
        
        if (changed_el.value != '') {
            var url = VS.getTaggedReferralUrl(VS.request_host,VS.request_path,VS.share_utm,changed_el.value);
            simple_bitlyfy(url);
            YUI.Dom.setStyle(VS.green_checks, 'display', 'inline');
            // YUI.Dom.setStyle(VS.email_containers, 'background', '#ffffff');
        } else {
            YUI.Dom.setStyle(VS.green_checks, 'display', 'none');
            // YUI.Dom.setStyle(VS.email_containers, 'background', '#dddddd');
        }
        
        YUI.Dom.batch(VS.eboxes, function (el) { //nimit
            if (changed_el.id != el.id) {
                el.value=changed_el.value;
            }
        });
    };
})();

