

$jq = jQuery.noConflict();

var acalendar;

function imageEditNew(){
    var pop = new Popup();
    pop.setWidth(650);
    pop.setHeight(500);
    pop.setAppendTo($("stage"));
    $jq.get('/editimage',
    {
        month: $jq("#hideMonth").val()
    },
    function(data){
        pop.addHTML(data);
        pop.setTitle("Edit Image");
        pop.render();
    },
    'html'
    );
}

function betaFeedback(){
    window.location = "/betafeedback";
//    betawindow = window.open("/betafeedback","betafeedback","status=1,width=350,height=150");
//    betawindow.getElementById("hidePage").value = window.location.toString();
}
function betaHelp(){
    var pop = new Popup();
    pop.setWidth(450);
    pop.setHeight(300);
    pop.setAppendTo($("stage"));
    pop.addHTML("<div><p style=\"font-weight: bold;\">You will only get this popup once.  To view again, please click the \"Beta Help\" link in the footer.</p><p>Please use the feedback link at the bottom of each page to submit errors, site suggestions or general feedback.</p>Use the following credit card information during the checkout process: <br />Card #: 4445999922225<br />Experation: 01/12<br />CVV2: 999</div>");
    pop.setTitle("Attention Beta Testers!");
    pop.render();
}

function showLinkPop(url, wid, hei){
    var pop = new Popup();
    var tmpTitle = url.replace("/","");
    var title =  tmpTitle.charAt(0).toUpperCase()+tmpTitle.substring(1,$F("hideMonth").length).toLowerCase();

    pop.setWidth(wid);
    pop.setHeight(hei);
    pop.setAppendTo($("stage"));
    
    $jq.get(url,
    {
        },
        function(data){
            pop.addHTML(data);
            pop.setTitle(title);
            pop.render();
        },
        'html'
        );
    
}

function monthsDone(){
    var firstMonth = null;
    $jq(".selectMonthBox").each(function(){
        if(!$jq(this).hasClass("selectMonthCompleteBox") && firstMonth == null){
            
            var months = $jq(this).attr("id").toString().split("_");
            firstMonth = months[1];

        }
    });
    
    $jq("#goToReview").unbind();

    if(firstMonth){
        $jq("#goToReview").click(function(){
            getCalendar(firstMonth);
        }).val("Continue");
        return true;
    } else{
        $jq("#goToReview").click(function(){
            selectCustomize();
        }).val("Checkout");
        return true;
    }
    return false;
}

function businessInfoNew(){
	
    var pop = new Popup();
    pop.setWidth(570);
    pop.setHeight(410);
    pop.setAppendTo($("stage"));
	
    $jq.get('/addfooter',
    {
        month: $jq("#hideMonth").val()
    },
    function(data){
        pop.addHTML(data);
        pop.setTitle("Business &amp; Contact Information");
        pop.render();


    },
    'html'
    );
}

function resetBusinessInfo(){
    $jq.get('/resetfooter',
    {},
        function(data){
            location.reload(true);
        },
        'html'
        );
	
}

function selectStock(){
    var pop = new Popup();
    pop.setWidth(492);
    pop.setHeight(290);
    pop.setAppendTo($("stage"));
	
    $jq.get('/imageselect',
    {
        type: 2
    },
    function(data){
        pop.addHTML(data);

        pop.setTitle("Stock Images");
        pop.render();
        $jq("#s-images").jCarouselLite({
            btnNext: "#moveRight",
            btnPrev: "#moveLeft",
            visible: 1
        });
        //need to attach an event to all images and handle the loading when the user clicks
        $jq(".stockImageElement").click(function(){
            var sizedImage = this.src.replace("_tn","");
            setImage(sizedImage);
            var imageID = this.id.split("_");
            new Ajax.Request(
                '/setimage',
                {
                    method: 'post',
                    parameters: {
                        month: $F("hideMonth"),
                        imageID: imageID[1]
                    },
                    onSuccess: function(transport){
                        json = transport.responseText.evalJSON();
                        try{
                            if($("editImageButton")){
                                $("editImageButton").hide();
                            }
                            if($("actualImage").src != "/images/defaultImage.png"){
                                $("selectMonthBox_"+$F("hideMonth")).addClassName("selectMonthCompleteBox");
                            }
                            monthsDone();
                        }catch(ex){
                            alert(ex);
                        }
                        closePop();
                    }
                }
                );
        //					closePop();
        });
    },
    'html'
    );
	

}

function myAccount(){
    window.location = "/store/customer/account/";
//    var pop = new Popup();
//    pop.setWidth(750);
//    pop.setHeight(400);
//    pop.setAppendTo($("stage"));
//
//    $jq.get('/editaccount',
//        null,
//        function(data){
//            pop.addHTML(data);
//            pop.setTitle("My Account");
//            pop.render();
//            Event.observe($("updateUserSubmit"),'click',function(){
//                var formElements = new Hash($('editAccountForm').serialize(true));
//                new Ajax.Request(
//                    '/editaccountpost',
//                    {
//                        method: 'post',
//                        parameters: formElements,
//                        onSuccess: function(transport){
//                            json = transport.responseText.evalJSON();
//                        //do something here
//                        }
//                    }
//                    );
//            });
//        },
//        'html'
//        );
}

function isLoggedIn(){
    if($("loginLogout").innerHTML == "Logout"){
        return true;
    }else{
        return false;
    }

}

function loginNew(){
    var pop = new Popup();
    pop.setWidth(600);
    pop.setHeight(230);
    pop.setAppendTo($("stage"));
		
    $jq.get('/account',
        null,
        function(data){
            pop.addHTML(data);
            pop.setTitle("Login");
            pop.render();
            $("userName").focus();
            Event.observe($("loginSubmit"),'click',function(){
                if(!$F("userName") || !$F('passWord')){
                    throwError("Please enter both Username and Password");
                    return false;
                }
                $("loginSubmit").disabled = true;
                
                new Ajax.Request(
                    '/aauth',
                    {
                        method: 'post',
                        parameters: {
                            requestedAction: "login",
                            email: $F("userName"),
                            passWord: $F('passWord')
                        },
                        onSuccess: function(transport){
                            json = transport.responseText.evalJSON();
                            if(json.success == true){
                                addLoggedInBlock();
                            }else{
                                $("loginSubmit").disabled = false;
                                throwError(json.errormsg);
                            }
                        }
                    }
                    );
                return true;
					
            });
            Event.observe($("passWord"),'keyup',function(e){
                if(e.keyCode != '13'){
                    return false;
                }
                if(!$F("userName") || !$F('passWord')){
                    throwError("Please enter both Username and Password");
                    return false;
                }
                $("loginSubmit").disabled = true;
                new Ajax.Request(
                    '/aauth',
                    {
                        method: 'post',
                        parameters: {
                            requestedAction: "login",
                            email: $F("userName"),
                            passWord: $F('passWord')
                        },
                        onSuccess: function(transport){
                            json = transport.responseText.evalJSON();
                            if(json.success == true){
                                addLoggedInBlock();
                            }else{
                                $("loginSubmit").disabled = false;
                                throwError(json.errormsg);
                            }
                        }
                    }
                    );
                return true;

            });
            Event.observe($("resetPassLink"),"click",function(){
                window.location = "/store/default/customer/account/forgotpassword/";
            });
            Event.observe($("createUserSubmit"),"click", function(){
                if(!validatePassword($F("newPassword"),$F("newPassword2"))){
                    throwError("Your passwords do not match");
                    return false;
                }
                if(!$F("email") || !$F("newPassword") || !$F("newPassword2") || !$F("firstname") || !$F("lastname") ){
                    throwError("You must fill out all the information before creating an account");
                    return false;
                }
                //                var formElements = new Hash($('createForm').serialize(true));
                $("createUserSubmit").disabled = true;
                new Ajax.Request(
                    '/aauth',
                    {
                        method:'post',

                        parameters: {
                            requestedAction: "addaccount",
                            firstname: $F("firstname"),
                            lastname: $F("lastname"),
                            email: $F("email"),
                            passWord: $F("newPassword")
                        },
                        onSuccess: function(transport){
                            json = transport.responseText.evalJSON();
                            if(json.success == true){
                                addLoggedInBlock();
                            }else{
                                $("createUserSubmit").disabled = false;
                                alert(json.errormsg);
                            }
                        }
                    }
                    );
            });
        },
        'html'
        );
		


}

function addLoggedInBlock(){
    location.reload();
//    new Ajax.Request(
//        '/getloggedinblock',
//        {
//            method:'post',
//            onSuccess: function(transport){
//                $('loggedInBlock').update(transport.responseText);
//                closePop();
//            }
//        });
}
function logOut(){
    new Ajax.Request(
        '/aauth',
        {
            method:'post',
            parameters: {
                requestedAction: "logout"
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                //                addLoggedInBlock();
                window.location = "/";
            }
        });
}

function validatePassword(pass1, pass2){
    if(pass1 == pass2){
        return true;
    }else{
        return false;
    }
}

function getStarted(){
	
    var pop = new Popup();

	
    var dropDown = new Element("select",{
        'name':'initStart',
        'id':'initStart'
    });

    var month=new Array(12);
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";

    var today = new Date();
    for (var x = 0; x < 12; x++){
        var newDate = new Date();
        newDate.setDate(1);
        newDate.setMonth(today.getMonth() + x);
		
        dropDown.appendChild(new Element("option",
        {
            'value':month[newDate.getMonth()] + " " + newDate.getDate() + " " + newDate.getFullYear()
        }
        ).update(month[newDate.getMonth()] + " - " + newDate.getFullYear())
            );
    }
	
    pop.addContent(new Element("div").update("What month would you like your calendar to begin?"));
    pop.addContent(dropDown);
    var goButton = new Element("input",{
        'type':'button',
        'value': 'Go'
    }).observe('click',function(event){
        startNewCal();
    });
    pop.addContent(goButton);
	
    pop.setAppendTo($("stage"));
    pop.setWidth(400);
    pop.setHeight(100);
    pop.setTitle("Select a Start Month");
    pop.render();
}

function throwError(msg){
    alert(msg);
}

function logoClick(){
    window.location = "/start";
}
function startNewCal(){
    if(($F("calName") == "" || $F("calName") == "Enter a name for your calendar" ) || $F("initStart") == ""){
        throwError("Please specify the calendar name and the start month");
        return false;
    }
   
    var startDate = $F("initStart");
    new Ajax.Request(
        '/startcal',
        {
            method:'post',
            parameters: {
                calName : $F('calName'),
                startDate: startDate
            },
            onSuccess: function(transport){
                window.location = "/";
            }
        }
        );
    return true;
}

function getPageFlex(){
    new Ajax.Request(
        '/getpageflex',
        {
            method:'post',
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                alert("Thanks for sending me to the PageFlex server. \nJob: "+ json.jobID);
            }
        }
        );
}

function addCustomText(elem){
    new Ajax.Request(
        '/addcustomtext',
        {
            method:'post',
            parameters: {
                month: $F("hideMonth"),
                day: $F("hideDay"),
                customText: $F(elem),
                customPos: $(elem).id
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                getCalendar();
            }
        }
        );
}

function addCustomCoverText(elem){
    $("calCoverTitle").innerHTML = $F("editCoverText");
}

function selectBindery(){
    //call the selectbindery through AJAX and pass in the bindery option selected then move to design.
    if($F("hideBindery") == ""){
        throwError("Please select before proceeding.");
        return false;
    }
    pleaseWait();
    new Ajax.Request(
        '/selectbindery',
        {
            method:'post',
            parameters: {
                binderyID: $F("hideBindery")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                window.location = "/";
            }
        }
        );
    return true;
        
}

function selectCustomize(){
    if(!isLoggedIn()){
        throwError("You must be logged in");
        loginNew();
        return false;
    }
    var pop = new Popup();
    pop.setAppendTo($("stage"));
    pop.setWidth(200);
    pop.setHeight(100);
    pop.setTitle("Please Wait");
    pop.setRemoveClose(true);
    pop.addHTML("<span>Please wait while we process your calendar</span><div style=\"text-align: center;\"><img src=\"/images/120837393833.gif\" /></div>");
    pop.render();
	
    new Ajax.Request(
        '/selectcustomize',
        {
            method:'post',
            parameters: {},
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                if(json.success == true){
                    window.location = "/review";
                }else{
                    closePop();
                    if(json.errormsg){
                        throwError(json.errormsg);
                    }else{
                        throwError("Opps, something went wrong");
                        window.location = "/";
                    }
                }
            },
            onFailure: function (){
                closePop();
                throwError("Opps, something went wrong");
            }
        }
        );
    return true;
}

function pleaseWait(){
    var pop = new Popup();
    pop.setAppendTo($("stage"));
    pop.setWidth(200);
    pop.setHeight(100);
    pop.setTitle("Please Wait");
    pop.setRemoveClose(true);
    pop.addHTML("<span>Please wait while we process your calendar</span><div style=\"text-align: center;\"><img src=\"/images/120837393833.gif\" /></div>");
    pop.render();
}

function selectReview(){
    pleaseWait();
    new Ajax.Request(
        '/selectreview',
        {
            method: 'post',
            parameters: {},
            onSuccess: function (transport){
                json = transport.responseText.evalJSON();
                if(json.success == true){
                    window.location = json.redirectUrl;
                }else{
                    $("loginSubmit").disabled = false;
                    closePop();
                    if(json.errormsg){
                        throwError(json.errormsg);
                    }else{
                        throwError("Opps, something went wrong");
                        window.location = "/";
                    }
                }
            },
            onFailure: function (){
                closePop();
                throwError("Opps, something went wrong");
            }
        }
        );
}

function selectLayout(){
    if($F("hideLayout") == ""){
        throwError("Please select a format before proceeding.");
        return false;
    }
    if($F("footerEmpty") == 1 && $F("hideLayout") != 1){
        if(!confirm("You will lose your business info by switching to this new layout.\n\n Are you sure you want to change?")){
            return false;
        }
    }
    pleaseWait();
    new Ajax.Request(
        '/selectlayout',
        {
            method:'post',
            parameters: {
                layoutID: $F("hideLayout")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                window.location = "/";
            }
        }
        );
    return true;
}

function cart(){
    if($F("hideLayout") == ""){
        throwError("Please select a quantity before proceeding.");
        return false;
    }
    new Ajax.Request(
        '/selectlayout',
        {
            method:'post',
            parameters: {
                layoutID: $F("hideLayout")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                if(json.out > 0){
                    window.location = "/finishing";
                }else{
                    window.location = "/design";
                }
            }
        }
        );
    return true;
}

function saveCal(){
    new Ajax.Request(
        '/savecalendar',
        {
            method:'post',
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                throwError("Calendar Saved");
            }
        }
        );
}

function getSavedCal(){
    new Ajax.Request(
        '/startcal',
        {
            method:'post',
            parameters: {
                calID: $F("userCals")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                window.location = "/";
            }
        }
        );
//
//    new Ajax.Request(
//        '/getsavedcals',
//        {
//            method:'post',
//            onSuccess: function(transport){
//                json = transport.responseText.evalJSON();
//                //run the render script for the cals
//                renderSavedCals(json);
//            }
//        }
//        );
}

function renderSavedCals(scJSON){
    var popup = new Popup();
    popup.setWidth(400);
    popup.setHeight(400);
    popup.setAppendTo($("stage"));
	
    scJSON.collect(
        function(s) {
            var tmpDiv = new Element("div");
            tmpDiv.update(s);
            Event.observe(tmpDiv,"click",
                function(){
                    new Ajax.Request(
                        '/startcal',
                        {
                            method:'post',
                            parameters: {
                                calID: s
                            },
                            onSuccess: function(transport){
                                json = transport.responseText.evalJSON();
                                window.location = "/";
                            }
                        }
                        );
                }
                );
            popup.addContent(tmpDiv);
        });
    popup.render();
	
}

function takeTo(place){
    if(place == "index"){
        place = "";
    }
    window.location = "/"+place;
}

function selectTheme(){
    if($F("hideTheme") == ""){
        throwError("Please select a theme before proceeding.");
        return false;
    }
    pleaseWait();
    new Ajax.Request(
        '/selecttheme',
        {
            method:'post',
            parameters: {
                themeID: $F("hideTheme")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                window.location = "/cover";
            }
        }
        );
    return true;
}

function setCoverTextPosition(elem){
    if(!elem){
        $("hideTextPosition").value = "textPosition_bottom";
        return true;
    }
    $("hideTextPosition").value = $(elem).id;
    if($(elem).id == "textPosition_top"){

        $("calCoverTitle").setStyle({
            top: '0px',
            bottom: 'auto'
        });
        $("picturewindow").setStyle({
            bottom: '0px',
            top: 'auto'
        });

    }else if($(elem).id == "textPosition_bottom"){

        $("calCoverTitle").setStyle({
            bottom: '0px',
            top: 'auto'
        });
        $("picturewindow").setStyle({
            top: '0px',
            bottom: 'auto'
        });
    }
    return true;
}

function selectCover(loc){
    var fontStyle = $("calCoverTitle").getStyle("fontFamily");
    new Ajax.Request(
        '/selectcover',
        {
            method:'post',
            parameters: {
                customText: $F("editCoverText"),
                customTextColor: $F("pickacolor"),
                customTextFont: fontStyle,
                customTextPosition: $F("hideTextPosition")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                window.location = loc;
            }
        }
        );
}

function addEconToDay(elem){
    var imageID = $(elem).id.toString().split("_");
    var imagePath = $(elem).src;
    if(!imageID[1]){
        return true;
    }
    new Ajax.Request(
        '/setecon',
        {
            method:'post',
            parameters: {
                day: $F("hideDay"),
                month: $F("hideMonth"),
                imagePath: imagePath,
                imageID: imageID
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                var calPos = parseInt(findDate($F("hideDay")))+1;
                var newImg = new Element("img",{
                    'src' : imagePath,
                    'class' : 'econDay'
                });
                
                if(imageID[1] < 0){
                    jQuery("#dayIcon_"+calPos+" img").remove();
                    $("dayIcon_"+calPos).update();
                }else{
                    $("dayIcon_"+calPos).update();
                    $("dayIcon_"+calPos).appendChild(newImg);
                }
                
            }
        }
        );
    return true;
}

function removeEconFromDay(){
    var calPos = parseInt(findDate($F("hideDay")))+1;
    if($("dayIcon_"+calPos).childElements().length == 0){
        throwError("No icon on this day");
        return false;
    }
    new Ajax.Request(
        '/removeecon',
        {
            method:'post',
            parameters: {
                day: $F("hideDay"),
                month: $F("hideMonth")
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                var calPos = parseInt(findDate($F("hideDay")))+1;
                $("dayIcon_"+calPos).childElements().collect(function(i){ 
                    $(i).remove();
                });
            }
        }
        );
    return true;
}

function addHolidays(){
    var holidayButton = $("addHolidays");
    var addRemove = "Add";
    var newVal = "Remove Holidays";
    if(holidayButton.value == "Remove Holidays"){
        addRemove = "Remove";
        newVal = "Add Holidays";
    }
	
    new Ajax.Request(
        '/addholidays',
        {
            method:'post',
            parameters: {
                holidayGroupID: 1,
                addRemove: addRemove
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                if(json.success == false){
                    alert(json.errorMsg);
                }
                holidayButton.value = newVal;
                getCalendar();
            }
        }
        );
}
function getEnvImage(){
    
    if(acalendar.envTip != ""){
        jQuery("#envTipText").html(acalendar.envTip);
        var elHeight = $("envTipText").getHeight() / 2;

        jQuery("#envTipText").css("top","50%");
        jQuery("#envTipText").css("marginTop","-"+elHeight+"px");

        jQuery("#enviroTip").css("visibility","visible");
    }else{
        jQuery("#enviroTip").css("visibility","hidden");
    }
}

function selectMonth(){
    var monthJSON = acalendar.monthData;

    //reset the day drop down
    if($("editDay")){
        $("editDay").update();
    }
	
    getTopImage();
    getBottomImage();
    getEnvImage();
    
    var firstDay = null;

    for(var x=0; x < 35; x++){
        var dayPos = parseInt(x+1);
		
        //get the first day of the month
        if(firstDay == null && monthJSON.allDays[x].dateType == "day"){
            firstDay = x;
        }
        //clear the custom text
        $("dayText1_"+dayPos).update();
        $("dayText2_"+dayPos).update();
        $("dayText3_"+dayPos).update();
				
        //clear the emoticon
        $("dayIcon_"+dayPos).update();
		
        //clear the CSS
        $("dayNum_"+dayPos).removeClassName("trailDay");
        $("dayNum_"+dayPos).removeClassName("leadDay");
        $("dayNum_"+dayPos).removeClassName("day");
		
        //add the day number with CSS
        $("dayNum_"+dayPos).addClassName(monthJSON.allDays[x].dateType);
        $("dayNum_"+dayPos).update(monthJSON.allDays[x].display);

        //add custom text
        if(monthJSON.allDays[x].customText){

            if(monthJSON.allDays[x].customText[0]){
                $("dayText1_"+dayPos).update(monthJSON.allDays[x].customText[0].customText);
                $("dayText1_"+dayPos).setStyle({
                    'color': monthJSON.allDays[x].customText[0].fontColor
                });
                $("dayText1_"+dayPos).setStyle({
                    'fontFamily': monthJSON.allDays[x].customText[0].fontFamily
                });
				
				
            }
            if(monthJSON.allDays[x].customText[1]){
                $("dayText2_"+dayPos).update(monthJSON.allDays[x].customText[1].customText);
				
                $("dayText2_"+dayPos).setStyle({
                    'color': monthJSON.allDays[x].customText[1].fontColor
                });
                $("dayText2_"+dayPos).setStyle({
                    'fontFamily': monthJSON.allDays[x].customText[1].fontFamily
                });
				
            }
            if(monthJSON.allDays[x].customText[2]){
                $("dayText3_"+dayPos).update(monthJSON.allDays[x].customText[2].customText);
				
                $("dayText3_"+dayPos).setStyle({
                    'color': monthJSON.allDays[x].customText[2].fontColor
                });
                $("dayText3_"+dayPos).setStyle({
                    'fontFamily': monthJSON.allDays[x].customText[2].fontFamily
                });
				
            }

            if(monthJSON.allDays[x].icon){
                $("dayIcon_"+dayPos).update();
                var imagePath = monthJSON.allDays[x].iconPath;
                var newImg = new Element("img",{
                    'src' : imagePath,
                    'class' : 'econDay'
                });
                $("dayIcon_"+dayPos).appendChild(newImg);
            }

        }
    }
	
    //handle the extra days
    if(monthJSON.allDays[35]){
        $("dayNum_29").update(monthJSON.allDays[28].display + "/" + monthJSON.allDays[35].display);
        $("dayNum_29").setStyle({
            "fontSize":"6pt"
        });
    }else{
        $("dayNum_29").setStyle({
            "fontSize":""
        });
    }
    if(monthJSON.allDays[36]){
        $("dayNum_30").update(monthJSON.allDays[29].display + "/" + monthJSON.allDays[36].display);
        $("dayNum_30").setStyle({
            "fontSize":"6pt"
        });
    }else{
        $("dayNum_30").setStyle({
            "fontSize":""
        });
    }
	

    if($("editDay")){
        var tmp = Element.select('div.dayNum','div.day');
		
		
        for (var i = 0; i < tmp.length; i ++){
            var selectedDay = false;
            var splitDay;
            var currentDay;
			
            if (tmp[i].innerHTML == $F('hideDay')){
                selectedDay = true;
            }

            if(tmp[i].innerHTML.indexOf("/")){
                splitDay = tmp[i].innerHTML.split("/");
				
                currentDay = splitDay[0];
            }else{
                currentDay = tmp[i].innerHTML;
            }
			
            $("editDay").appendChild(new Element('option',{
                'selected': selectedDay,
                'value': currentDay
            }).update($F("hideMonth").charAt(0).toUpperCase()+$F("hideMonth").substring(1,$F("hideMonth").length).toLowerCase()+" "+tmp[i].innerHTML));
        }
        setDay();
    }
	

	
    //show month name in the left nav sections
    if($$("span.editMonthName").length > 0){
        $$("span.editMonthName").collect(function(s){
            s.update($F("hideMonth").charAt(0).toUpperCase()+$F("hideMonth").substring(1,$F("hideMonth").length).toLowerCase());
        });
		
        $("monthDisplay").update("<div class=\"monthDisplayDiv\">"+$F("hideMonth").charAt(0).toUpperCase()+$F("hideMonth").substring(1,$F("hideMonth").length).toLowerCase()+"<br />"+monthJSON.year+"</div>");

        //only display the month and year above the calendar if the layout is hanging
        if(acalendar.layout.layoutID == 1){

            $("monthHangDisplay").update("<div>"+$F("hideMonth").charAt(0).toUpperCase()+$F("hideMonth").substring(1,$F("hideMonth").length).toLowerCase()+" "+monthJSON.year+"</div>");
            
            jQuery("#monthHangDisplay div").css("paddingTop","10px");

        }
    }
	
}

function setDay(){
    //TODO: need a hidden field to control what day is pre-selected
    var dayJSON = acalendar.monthData.allDays[findDate($F("editDay"))];

    $("hideDay").value = $F("editDay");
	
    $('editDay1','editDay2','editDay3').collect(function (s){
        s.value = "";
    });
    if(dayJSON.customText.length > 0){
        
        if(dayJSON.customText[0]){
            $("editDay1").value = dayJSON.customText[0].customText;
        }
        if(dayJSON.customText[1]){
            $("editDay2").value = dayJSON.customText[1].customText;
        }
        if(dayJSON.customText[2]){
            $("editDay3").value = dayJSON.customText[2].customText;
        }
    }
}

function setBackgroundColor(elem){
    $("calBackground").setStyle({
        'backgroundColor': elem
    });
	
    new Ajax.Request(
        '/setbackgroundcolor',
        {
            method: 'post',
            parameters: {
                month: $F("hideMonth"),
                color: elem
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
            }
        });
	
	
}

function setTextColor(elem,pos){
    //    var col = $(elem).getStyle("background-color");
    var col = elem;
    if(pos == "pickacolor"){
        setCoverTextColor(col);
        return true;
    }
    if(pos == "bgColor_1"){
        setBackgroundColor(col);
        return true;
    }
    tPos = pos.split("_");
    pos = tPos[1];
    var calPos = parseInt(findDate($F("hideDay")))+1;
    $("dayText"+pos+"_"+calPos).setStyle({
        'color' : col
    });

    new Ajax.Request(
        '/setcustomtextstyle',
        {
            method:'post',
            parameters: {
                month: $F("hideMonth"),
                day: $F("hideDay"),
                pos: pos,
                type: 'color',
                color: col
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
            }
        });
    return true;
}

function setCoverTextFont(font){
    $("calCoverTitle").setStyle({
        'fontFamily' : font
    });
    jQuery('#calCoverTitle').textfill({
        maxFontPixels: 70
    });
    verticalCenter();
}

function setCoverTextColor(elem){
    var col = elem;
    $("calCoverTitle").setStyle({
        'color' : col
    });
}

function setTextFont(elem, pos){
    var font = elem;
    var calPos = parseInt(findDate($F("hideDay")))+1;
    $("dayText"+pos+"_"+calPos).setStyle({
        'fontFamily' : font
    });
	
    new Ajax.Request(
        '/setcustomtextstyle',
        {
            method:'post',
            parameters: {
                month: $F("hideMonth"),
                day: $F("hideDay"),
                pos: pos,
                type: 'font',
                font: font
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
            }
        }
        );
	
}

function findDate(selectedDate){
    var findDay = null;
    for (var x = 0; x < acalendar.monthData.allDays.length; x++){
        if(findDay == null && acalendar.monthData.allDays[x].display == selectedDate && acalendar.monthData.allDays[x].dateType == "day"){
            findDay = x;
        }
    }
    return findDay;
}

function getCalendar(monthName){
    if(!monthName){
        monthName = $F("hideMonth");
    } else if (monthName != $("hideMonth")){
        $("hideDay").value = 1;
    }
    $("hideMonth").value = monthName;
    updateMonthSelected();
    new Ajax.Request(
        '/getcalendar',
        {
            method:'post',
            parameters: {
                month: monthName
            },
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                acalendar = json;
                selectMonth();
                monthsDone();
            }
        });
}

function updateMonthSelected(){
    $$(".selectMonthBox").collect(function(s){
        s.removeClassName("lightRedBorder");
    });
	
    $("selectMonthBox_"+$F("hideMonth")).addClassName("lightRedBorder");
}

function addImageWarning(){
    jQuery("<div id=\"imageWarn\" class=\"imageWarn\"><div style=\"padding-left: 30px;\">Uh-oh! The image you uploaded doesn't meet our print quality standards. To learn more, <a href=\"http://www.photoshopessentials.com/essentials/image-quality\" target=\"_blank\">click here</a></div><div id=\"imageWarnButton\"><input type=\"button\" value=\"Ok\" onclick=\"javascript: jQuery('.imageWarn').remove(); return true;\" /></div>").appendTo("#picturewindow");
//    $("imageWarn").opacity(".5");
}
function getTopImage(){

    if(acalendar){
        if(acalendar.monthData.topImage){

            setImage(acalendar.monthData.topImage.url);
            if(acalendar.effectiveRes < 250){
                addImageWarning();
            }else{
                jQuery(".imageWarn").remove();
            }
            if(acalendar.monthData.topImage.isCustom == true){
                if($("editImageButton")){
                    $("editImageButton").show();
                }
            }else{
                if($("editImageButton")){
                    $("editImageButton").hide();
                }
            }
        }else{

            setImage("/images/defaultImage.png");
            jQuery(".imageWarn").remove();
            if($("editImageButton")){
                $("editImageButton").hide();
            }
        }
    } else { //they are on the cover page
        setImage($F("coverImageUrl"));
    }
}

function getBottomImage(){
    if(acalendar.monthData.background){
        if(acalendar.monthData.background.url != null){
            $("bgImage").src = acalendar.monthData.background.url +"?" + Math.floor(Math.random()*999999+1);
        } else if (acalendar.monthData.background.colorHex){
			
            $("calBackground").setStyle({
                'backgroundColor': acalendar.monthData.background.colorHex
            });
        }
    }else{
        $("calBackground").setStyle({
            'backgroundColor': '#FFFFFF'
        });
    }
}

function addRedBorder(elem){
    //$("centerStage").select('img.layoutIcon').collect(function(s){
    //	s.removeClassName('redBorder');
    //});
    //	$(elem).select('img.layoutIcon').collect(function(s){ s.addClassName('redBorder');});
    //$(elem).addClassName('redBorder');
	
    eval($F("nextStepAdvance"));
	
}

function showFonts(btnElem, position){
    var id = jQuery(btnElem).attr("id");

    var eICP=jQuery(btnElem).position();

    if(jQuery("#" + id + "_pop").length == 0){
        jQuery.get(
            '/getfonts',
            function(data){
                jQuery(document.createElement("div")).attr("id","fontBg").css({
                    'position':'absolute',
                    'top':0,
                    'left':0,
                    'width':'100%',
                    'height':'100%'
                }).appendTo("body").click(function(){
                    jQuery("#" + id +"_pop").fadeOut('slow');
                    jQuery("#fontBg").hide();
                });
                jQuery(btnElem).after(jQuery(document.createElement("div")).attr("id",id + "_pop").css({
                    'position':'absolute',
                    'top':eICP.top+(jQuery(btnElem).outerHeight())+"px",
                    'left':(eICP.left)+"px",
                    'background-color':'white',
                    'width': '125px',
                    'z-index':9999
                }).html(data)).fadeIn('slow');
                jQuery(".fontSelection").each(function(){
                    jQuery(this).click(function(){
                        if(position == "cover"){
                            setCoverTextFont(jQuery(this).css("font-family"));
                        }
                        else{
                            setTextFont(jQuery(this).css("font-family"),position);
                        }
                        jQuery("#"+id+"_pop").hide();
                        jQuery("#fontBg").hide();
                    }).css({
                        "cursor":"pointer",
                        "border":"1px solid #CACACA",
                        "padding":"3px"

                    });
                    jQuery(this).hover(function(){ 
                        jQuery(this).css("backgroundColor","#CACACA");
                    }, function(){
                        jQuery(this).css("backgroundColor","");
                    })
                });
            },
            'html'
            );
    }else{
        jQuery("#fontBg").show();
        jQuery("#" + id+"_pop").fadeIn('slow');
    }
}
function checkcoverres(){
    jQuery.get(
        '/coverres',
        function(data){
            if(data < 250){
                addImageWarning();
            }
//            alert(data);
        });
}
function setImage(image){
    //	var imgOb = new Image();

    if(!image){
        image = '/images/defaultImage.png';
    }

    $('actualImage').setStyle({
        width: "auto",
        height: "auto"
    });
    $('actualImage').src = image +"?" + Math.floor(Math.random()*999999+1);
    $('actualImage').onload = function (){
        
        var bleed = 6;

        var c = $('actualImage').getDimensions();
        var cWidth = c["width"];
        var cHeight = c["height"];

        var frame = $("picturewindow").getDimensions();
        var frameWidth = frame["width"] + bleed;
        var frameHeight = frame["height"] + bleed;

        //figure out how much the height moves so the width can move to porportions
        var hRatio = parseInt(frameHeight)/parseInt(cHeight);
        var wRatio = parseInt(frameWidth)/parseInt(cWidth);

        var newHeight, newWidth;

        if(hRatio > wRatio){
            newHeight = cHeight * hRatio;
            newWidth = (cWidth / cHeight) * newHeight;
        }else{
            newWidth = cWidth * wRatio;
            newHeight = (cHeight / cWidth) * newWidth;
        }
        	
        $('actualImage').setStyle({
            width: newWidth+"px",
            height: newHeight+"px"
        });

        var moveX = 0 - (newWidth - (frameWidth-bleed)) / 2;
        var moveY = 0 - (newHeight - (frameHeight-bleed)) / 2;
        
        $('actualImage').setStyle({
            marginLeft: moveX + "px",
            marginTop: parseInt(0 - (bleed/2))+"px"
        });




    };
	
}

function clearImage(){
    $('actualImage').src = '';
}

function switchTab(selectedTab){
	
    var monthTab = $("customizeMonth");
    var dayTab = $("customizeDay");
    //    var globalTab = $("customizeGlobal");
	
    monthTab.hide();
    dayTab.hide();
    //    globalTab.hide();

    var tabs = $('tabDiv2').select('.newTabDiv').collect(function(s){
        return s.removeClassName('selected');
    });
	
    switch(selectedTab){
        case "month":
            tabs[0].addClassName('selected');
            monthTab.show();
            break;
        case "day":
            tabs[1].addClassName('selected');
            dayTab.show();
            break;
    //        case "global":
    //            tabs[2].addClassName('selected');
    //            globalTab.show();
    //            break;
    }
}

function businessInfo(){
    var cName, fName, lName, add1, add2, city, state, zip, phone, email, website, can, save;
    var popup = new Popup();
	
    var elems = new Hash({
        companyName: "Company Name",
        firstName: "First Name",
        lastName: "Last Name",
        address1: "Address 1",
        address2: "Address 2",
        city: "City",
        state: "State",
        zip: "Zip",
        phone: "Primary Phone Number",
        email: "Email Address",
        webSite: "Website Address",
        can: "Cancel",
        save: "Save"
    });

    var preselect = (acalendar.footerInfo.address.state) ? acalendar.footerInfo.address.state : "";
	
    var f1 = new Element("form",{
        'name':'f1',
        'id':'f1',
        'method':'post'
    });
    popup.setWidth(290);
    popup.setHeight(500);
	
    cName = new Element("div",{
        'id':'cNameDiv'
    }).update(
        new Element("input",{
            'id':'companyName',
            'name':'companyName',
            'value':(acalendar.footerInfo.companyName) ? acalendar.footerInfo.companyName : 'Company Name'
        })
        );
    f1.appendChild(cName);

    fName = new Element("div",{
        'id':'fNameDiv'
    }).update(
        new Element("input",{
            'id':'firstName',
            'name':'firstName',
            'value':(acalendar.footerInfo.firstName) ? acalendar.footerInfo.firstName : 'First Name'
        })
        );
    f1.appendChild(fName);
	
    lName = new Element("div",{
        'id':'lNameDiv'
    }).update(
        new Element("input",{
            'id':'lastName',
            'name':'lastName',
            'value':(acalendar.footerInfo.lastName) ? acalendar.footerInfo.lastName : 'Last Name'
        })
        );
    f1.appendChild(lName);
	
    add1 = new Element("div",{
        'id':'add1Div'
    }).update(
        new Element("input",{
            'id':'address1',
            'name':'address1',
            'value':(acalendar.footerInfo.address.address1) ? acalendar.footerInfo.address.address1 : 'Address 1'
        })
        );
    f1.appendChild(add1);
	
    add2 = new Element("div",{
        'id':'add2Div'
    }).update(
        new Element("input",{
            'id':'address2',
            'name':'address2',
            'value':(acalendar.footerInfo.address.address2) ? acalendar.footerInfo.address.address2 : 'Address 2'
        })
        );
    f1.appendChild(add2);
    city = new Element("div",{
        'id':'cityDiv'
    }).update(
        new Element("input",{
            'id':'city',
            'name':'city',
            'value':(acalendar.footerInfo.address.city) ? acalendar.footerInfo.address.city : 'City'
        })
        );
    f1.appendChild(city);
	
    state = getStates(preselect);
	
    zip = new Element("input",{
        'id':'zip',
        'name':'zip',
        'value':(acalendar.footerInfo.address.zip) ? acalendar.footerInfo.address.zip : 'Zip',
        'class': 'zipCode'
    });
	
    var tmpDiv = new Element("div");
    tmpDiv.appendChild(state);
    tmpDiv.appendChild(zip);
	
    f1.appendChild(tmpDiv);
	
    phone = new Element("div",{
        'id':'phoneDiv'
    }).update(
        new Element("input",{
            'id':'phone',
            'name':'phone',
            'value':(acalendar.footerInfo.phone) ? acalendar.footerInfo.phone : 'Primary Phone Number'
        })
        );
    f1.appendChild(phone);
	
    email = new Element("div",{
        'id':'emailDiv'
    }).update(
        new Element("input",{
            'id':'email',
            'name':'email',
            'value':(acalendar.footerInfo.email) ? acalendar.footerInfo.email : 'Email Address'
        })
        );
    f1.appendChild(email);
	
    website = new Element("div",{
        'id':'websiteDiv'
    }).update(
        new Element("input",{
            'id':'webSite',
            'name':'webSite',
            'value':(acalendar.footerInfo.webSite) ? acalendar.footerInfo.webSite : 'Website Address'
        })
        );
    f1.appendChild(website);
	
    can = new Element("input",{
        'type':'button',
        'value':'Cancel',
        'id':'biReset'
    });
    Event.observe(can,'click',function(){
        popup.close();
    });
    save = new Element("input",{
        'type':'button',
        'value':'Save',
        'id':'biSave'
    });
    Event.observe(save,'click',function(){
        //ajax to add footer
        var formElements = new Hash($('f1').serialize(true));
        formElements.collect(
            function(elem){
                if(elem.value == elems.get(elem[0])){
                    formElements.unset(elem[0]);
                }
            }
            );
		
        new Ajax.Request(
            '/footer',
            {
                method:'post',
                parameters: formElements,
                onSuccess: function(transport){
                    json = transport.responseText.evalJSON();
                    refreshFooter();
                    popup.close();
                }
            }
            );
    });
    f1.appendChild(can);
    f1.appendChild(save);
    popup.addContent(f1);
    popup.setAppendTo($('navWrapper'));
    popup.setTitle("Business &amp; Contact Information");
    popup.setTopPad(50);
    popup.render();
	
    Form.getElements($('f1')).collect(function (s){
        if(s.type != "button" || s.type != "select-one"){
            Event.observe(s,'focus',function(){
                if(s.value == elems.get(s.id)){
                    s.value = "";
                }
            });
            Event.observe(s,'blur',function(){
                if(s.value == ""){
                    s.value = elems.get(s.id);
                }
            });
        }
    });
}

function refreshFooter(){
    new Ajax.Request(
        '/getfooter',
        {
            method:'post',
            onSuccess: function(transport){
                json = transport.responseText.evalJSON();
                acalendar.footerInfo = json;
                $('fCompanyName').update(json.companyName);
                $('fName').update(json.firstName + " " + json.lastName);
                $('fAddress1').update(json.address.address1);
                $('fAddress2').update(json.address.address2);
                //TODO: check to ensure both city and state are populated before appending the comma between them
                $('fCityStateZip').update(json.address.city + ", " + json.address.state + " " + json.address.zip);
                $('fWeb').update(json.webSite);
                $('fEmail').update(json.email);
                $('fPhone').update(json.phone);

                if(json.footerImage && json.footerImage.url){
                    $('footerPicImage').src = json.footerImage.url +"?" + Math.floor(Math.random()*999999+1);
                    $('footerPicImage').show();
                }
				
                $$('.calendar').collect(function(s){
                    s.addClassName('calendarWithFoot');
                });
			
                $$('.dayWrap').collect(function(s){
                    s.addClassName('dayWrapWithFoot');
                });

                $("calFooter").show();
            }
        });
}

function getStates(preSelected){
    var states = {
        State: 'State',
        AK:'Alaska',
        AL:'Alabama',
        AR:'Arkansas',
        AZ:'Arizona',
        CA:'California',
        CO:'Colorado',
        CT:'Connecticut',
        DC:'D.C.',
        DE:'Delaware',
        FL:'Florida',
        GA:'Georgia',
        HI:'Hawaii',
        IA:'Iowa',
        ID:'Idaho',
        IL:'Illinois',
        IN:'Indiana',
        KS:'Kansas',
        KY:'Kentucky',
        LA:'Louisiana',
        MA:'Massachusetts',
        MD:'Maryland',
        ME:'Maine',
        MI:'Michigan',
        MN:'Minnesota',
        MO:'Missouri',
        MP:'Marianas',
        MS:'Mississippi',
        MT:'Montana',
        NC:'North Carolina',
        ND:'North Dakota',
        NE:'Nebraska',
        NH:'New Hampshire',
        NJ:'New Jersey',
        NM:'New Mexico',
        NV:'Nevada',
        NY:'New York',
        OH:'Ohio',
        OK:'Oklahoma',
        OR:'Oregon',
        PA:'Pennsylvania',
        RI:'Rhode Island',
        SC:'South Carolina',
        SD:'South Dakota',
        TN:'Tennessee',
        TX:'Texas',
        UT:'Utah',
        VA:'Virginia',
        VT:'Vermont',
        WA:'Washington',
        WI:'Wisconsin',
        WV:'West Virginia',
        WY:'Wyoming'
    };
	
    var stateDrop = new Element("select",{
        'name': 'state',
        'id': 'state'
    });
    $H(states).collect(
        function(s){
            var dselected = false;
            if(s[0] == preSelected){
                dselected = true;
            }
            stateDrop.appendChild(new Element("option",{
                'selected':dselected,
                'value':s[0]
            }).update(s[1]));
        });
    return stateDrop;
}

function clearRequired(thisObj){
    $(thisObj).value = '';
	
}