 /**
 * Swap a container out for another.
 * 
 * @param url the url to load the new container
 * @param container the old container to replace
 * @param callback a function to call after the container has been loaded
 * @return void
 */
function doContainerSwap(url, container, callback) {
    $(container).hide();    
    // Because Refreshing is so 2009...
    $.get(url, function(data) { 
        $(container).after(data);
        callback();
    });
}

function bindNavHover() {
    $("#main_nav li a").each(function() {
        // preload hover states
        var img = new Image();
        img.src = "/resources/" + $(this).attr('img') + '_over.png';
        if($(this).hasClass('current')) {
            $(this).addClass($(this).attr('img') + '_over');
        }
    }); 
    $("#main_nav li a").hover(
        function() {
            if(!$(this).hasClass('current')) {
                $(this).addClass($(this).attr('img') + '_over');
                $(this).removeClass($(this).attr('img'));
            }
        },
        function() {
            if(!$(this).hasClass('current')) {
                $(this).removeClass($(this).attr('img') + '_over');
                $(this).addClass($(this).attr('img'));
            }
        }
    );
}

function doPageLoad(uri, secure, useHistory) {
    var protocol = (secure ? 'https://' : 'http://');
    var host     = window.location.host;
    
    // Do the page reload
    if(useHistory) {
        window.location.href = protocol + host + uri;
    } else {
        window.location.replace(protocol + host + uri);
    }
}

function clearFormElements(el) {
    $(el).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
}

/**
 * Click event handler for 'add to shopping cart' button.
 */
function handleCartItemClick(id) {
    //loadingOverlay.load();
    $.post('/cart/add', {id: id}, function(data, status, xhr) {
        switch(xhr.status) {
            case 202 : // ACCEPTED
                //loadingOverlay.close();
                data = data.replace(" ", "");
                $("#items_in_cart").show();
                $("#items_in_cart").html('(' + data + ')');
                setTimeout("addedOverlay.load();setTimeout(\"addedOverlay.close();\", 1000);", 300);
                break;
            case 204 : // Item already in cart
                alert("Item already in cart.");
                break;
            default :
                alert("Error adding item to cart.");
                break;
        }
        
    });
}

/**
 * Hover event handler for list items.
 */
function handleItemHover() {
    $(this).toggleClass("item_hover");
}

/**
 * Click event handler for list items.
 * 
 * @param event the click event
 */
function handleItemClick(event) {
    // If the cart was clicked divert to the event handler
    // for that. We do this here to make it easier to find
    // which item was clicked without embedding it into the
    // cart div itself.
    
    if(event.target.id == 'cart_item') {
        var id = event.currentTarget.id;
        handleCartItemClick(id);
    } else {
        doPageLoad('/Program/' + event.currentTarget.id, false, true);
    }
}

/**
 * Click event handler for list items.
 * 
 * @param event the click event
 */
function handleStudioItemClick(event) {
    // If the cart was clicked divert to the event handler
    // for that. We do this here to make it easier to find
    // which item was clicked without embedding it into the
    // cart div itself.
    
    if(event.target.id == 'cart_item') {
        var id = event.currentTarget.id;
        handleCartItemClick(id);
    } else {
        doPageLoad('/studio71/' + event.currentTarget.id, false, true);
    }
}


function handleBreadcrumbClick(event) {
    var el = $(event.target);
    var id = el.parent().attr('id');
    doPageLoad(id, false, true);
}

var loadingOverlay = null;
var addedOverlay   = null;

function addOverlay() {
    if($.browser.msie) {
        loadingOverlay = {
        	close: function() {
        		overlay.close();  
        		return false;
        	}, 
        	load: function() {
        		overlay = $("#ajax_loading").overlay({
		            mask: {
		                color:'#000',
		                loadSpeed:200,
		                spacity:0.5
		            },
		            oneInstance: false,
		            api: true
		        });
        		overlay.load();
        		return false;
        	}};
        addedOverlay   = {
        	close: function() { 
        		//alert('closing');        		
        		overlay.close();        		
        		return false;
        	}, 
        	load: function() {
        		//alert('Added to Cart!');
        		overlay = $("#program_added").overlay({
		            mask: {
		                color:'#000',
		                loadSpeed:200,
		                spacity:0.5
		            },
		            oneInstance: false,
		            api: true
		        });
        		overlay.load();
        		return false;
        	}
        };
    } else {
        loadingOverlay = $("#ajax_loading").overlay({
            mask: {
                color:'#000',
                loadSpeed:200,
                spacity:0.5
            },
            oneInstance: false,
            api: true
        });
        addedOverlay = $("#program_added").overlay({
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.5
            },
            oneInstance: false,
            api: true
        });
    }
}

var overlay;
function initOverlay() {
    // select the overlay element - and "make it an overlay"
    $("#overlay").overlay({load:false});
}

function doOverlay(elementId) {
    $('#overlay_contents').html($('#'+elementId).html());
    if(overlay === undefined) {
        overlay = $("#overlay").overlay();
    }
    overlay.load();
}

/**
 * Add event handlers to listed items.
 * 
 * @return void
 */
function addItemHandler() {
    //$("table#items > tbody > tr").hover(handleItemHover, handleItemHover);
    $("table#items > tbody > tr").click(handleItemClick);
    $("table#items_studio > tbody > tr").click(handleStudioItemClick);
}


function getParameterByName() {
	var match = RegExp('[?#]'+'([^&]*)').exec(window.location.search);	
	return match && decodeURIComponent(match[1].replace(/\+/g, ' '));	
}

/**
 * Add event handlers to tab panels.
 * 
 * @return void
 */
function addTabHandler() {
    var path = location.href;
    var initIndex = 0;
    var href = "#";
    aPath = path.split("#");
    if(aPath.length > 1) {
        href += aPath[aPath.length - 1];
    }
    
    //alert(getParameterByName());
    
    $("ul.tabs").each(function(i,v) {
        $(this).find("li a").each(function(j,w) {
            if($(this).attr('href') == href) {
                initIndex = j;
            }
        });
    });
    var options = {
        history: true,
        onBeforeClick: function() {
            $("ul.tabs > li").removeClass('current');
        },
        onClick: function(event, index) {
            this.getTabs().eq(index).parents('li').addClass('current');
        }
    };
    $("ul.tabs").tabs("div.panes > div", options);
    $("ul.grandchild_tabs").tabs("> .tab_content_container");
}

function addBreadcrumbHandler() {
    $("div#breadcrumb div.parent").click(handleBreadcrumbClick);
}

function addTooltipHandler() {
    $("#search_bar a").each(function() {
        var img = new Image();
        img.src = "/resources/images/" + $(this).attr('img') + "_over.png";
    });
    $("#search_bar a").tooltip();
}

function preloadImages() {
    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();
    var img4 = new Image();
    var img5 = new Image();
    var img6 = new Image();
    var img7 = new Image();
    var img8 = new Image();
    var img9 = new Image();
    var img10 = new Image();
    var img11 = new Image();
    var img12 = new Image();
    var img13 = new Image();
    var img14 = new Image();
    var img15 = new Image();
    img1.src = '/resources/images/nav_programs_over.png';
    img2.src = '/resources/images/nav_publications_over.png';
    img3.src = '/resources/images/nav_custom_programs_over.png';
    img4.src = '/resources/images/nav_law_schools_over.png';
    img5.src = '/resources/images/nav_donate_over.png';
    img6.src = '/resources/images/nav_about_over.png';
    img7.src = '/resources/images/nav_contact_over.png';
    img8.src = '/resources/images/add_to_cart_over.png';
    img9.src = '/resources/images/sorta.png';
    img10.src = '/resources/images/sortd.png';
    img11.src = '/resources/images/search_bar_print_over.png';
    img12.src = '/resources/images/add_to_cart_over.png';
    img13.src = '/resources/images/search_bar_account_over.png';
    img14.src = '/resources/images/program_add_to_cart_over.png';
    img15.src = '/resources/images/search_bar_cart_over.png';
}

function checkForCartItems() {
	//alert('checking for cart items');	
    $.get('/cart/numitems', {id: 0}, function(data, status, xhr) {
    	//alert(data);
    	data = data.replace(" ", "");
        if(data != '0') {
            $("#items_in_cart").show();
            $("#items_in_cart").html('(' + data + ')');
        } else {
        	$("#items_in_cart").hide();
        }
    });
}









phoneFormat = function (oField) { // formats a phone number as (###) ###-#### --- call using phoneFormat(event.srcElement);
    //-----------------------------------------------------------------------------------------------------------------------------
    // Author: CRMCulture
    // Description: formats a phone number as (###) ###-#### --- call using phoneFormat(event.srcElement);
    // WILL UPDATE ONLY IF COUNTRY = USA OR COUNTRY = CAN
    // Example Calling syntax:   phoneFormat(event.srcElement);  
    TranslateMask = function (s) {
        /// TranslateMask() will step through each character of an 
        /// input string and pass that character to the 
        /// TranslatePhoneLetter() helper method
        /// <param name="s">Input string to translate</param>
        var ret = "";
        //loop through each char, and pass it to the translation method
        for (var i = 0; i < s.length; i++) {
            ret += TranslatePhoneLetter(s.charAt(i))
        }
        return ret;
    }
    TranslatePhoneLetter = function (s) {
        /// TranslatePhoneLetter() takes a character and returns the 
        /// equivalent phone number digit if it is alphanumeric
        /// <param name="s">Character to translate</param>
        var sTmp = s.toUpperCase();
        var ret = s;

        switch (sTmp) {
            case "A":
            case "B":
            case "C":
                ret = 2;
                break;
            case "D":
            case "E":
            case "F":
                ret = 3;
                break;
            case "G":
            case "H":
            case "I":
                ret = 4;
                break;
            case "J":
            case "K":
            case "L":
                ret = 5;
                break;
            case "M":
            case "N":
            case "O":
                ret = 6;
                break;
            case "P":
            case "Q":
            case "R":
            case "S":
                ret = 7;
                break;
            case "T":
            case "U":
            case "V":
                ret = 8;
                break;
            case "W":
            case "X":
            case "Y":
            case "Z":
                ret = 9;
                break;
            default:
                ret = s;
                break;
        }
        return ret;
    }
    //var countryField = crmForm.all.address1_country.DataValue;
    // Get the field that fired the event
    //var oField = event.srcElement;
    // Verify that the field is valid
    if (typeof (oField) != "undefined" && oField != null) {
            
            // Remove any special characters
            var sTmp = oField.replace(/[^0-9,A-Z,a-z]/g, "");
            // Translate any letters to the equivilant phone number, if method is included
            try {
                if (sTmp.length <= 10) {
                    sTmp = TranslateMask(sTmp);
                } else {
                    sTmp = TranslateMask(sTmp.substr(0, 10)) + sTmp.substr(10, sTmp.length);
                }
            }
            catch (e) {
            }

            // If the number is a length we expect and support, 
            // format the translated number
            switch (sTmp.length) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 8:
                case 9:
                    break;
                case 7:
                    return  sTmp.substr(0, 3) + "-" + sTmp.substr(3, 4);
                    break;
                case 10:
                    return "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
                    break;
                default:
                    return "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4) + " " + sTmp.substr(10, sTmp.length);
                    break;
            }
        
    }
}


//add an attendee to a cart item
//called by a super user in multi cart
function addAttendeeHandler() {

	$('.attendee_select').change(function(e) {	
		$this = $(this);
		var attendee = $this.val();
		var rowid = $this.attr('id');		
		
		$.post('/cart/assign', {attendee: attendee, rowid: rowid}, function(data, status, xhr) {
	        switch(xhr.status) {
	            case 202 : // ACCEPTED
	                $this.next().text('');
	                $("#items_in_cart").html('(' + data + ')');
	                break;
	            default :
	                alert("Error adding attendee to item.  Please try again.");
	                break;
	        }
	        
	    });
		
		return false;
	});

}

//function to email a program to a friend
//called from program detail pages & final checkout page (after processing)
function sendToFriend() {	
	
	$('.send_to_friend').live( 'click', function(e){
		e.preventDefault();
		$this = $(this);
		
		$this.hide();
		$("#friend_send_form_holder").show();
	});	
	
	//called from program detail pages
    $("#friend_send_form").bind("submit", function(e) {
    	e.preventDefault();	    		
   		
   		var break_out = false;

		if ($("#friend_input_name").val().length < 1) {
		    $("#error_name").show();
		    break_out = true;
		}
		if ($("#friend_input_email").val().length < 1) {
		    $("#error_email").show();
		    break_out = true;
		}
							
		if (!break_out)	{			
			$.ajax({
				type	: "POST",
				cache	: false,
				url		: "/Shop/Email",
				data	: $(this).serializeArray(),
				success	: function(data) {
					$('#friend_send_form_holder').html(data);
					$('#friend_send_form_holder').delay(4000).slideUp('slow');
				}
			});
		}   		   		
		
	});
	
	//called from final checkout page
	$("#friend_send_form_checkout").bind("submit", function(e) {
    	e.preventDefault();	    		
   		
   		var break_out = false;

		if ($("#friend_input_name").val().length < 1) {
		    $("#error_name").show();
		    break_out = true;
		}
		if ($("#friend_input_email").val().length < 1) {
		    $("#error_email").show();
		    break_out = true;
		}
							
		if (!break_out)	{			
			$.ajax({
				type	: "POST",
				cache	: false,
				url		: "/Shop/Email",
				data	: $(this).serializeArray(),
				success	: function(data) {
					$('#friend_send_form_holder_checkout').html(data);
					//$('#friend_send_form_holder_checkout').delay(4000).slideUp('slow');
				}
			});
		}   		   		
		
	});
}

//popups windows for faculty biographies
function facultyBios() {
	
	//hide links w/o content
	$('.faculty_read_more_trigger').each(function(e) {	
		$this = $(this);
		if ($this.parent().parent().children('.faculty_read_more').html() == '') {
			$this.replaceWith('<strong>'+$this.text()+'</strong>');
		}										
	});
	
	$('.faculty_read_more_trigger').live( 'click', function(e){		
		e.preventDefault();
		$this = $(this);		
		
		pop_content = $this.parent().parent().children(".faculty_read_more").html();
		
		//init overlay
		if (pop_content != '') {
			$('#overlay_contents').html(pop_content);
		    if(overlay === undefined) {
		        overlay = $("#overlay").overlay();
		    }
		    overlay.load();
		}
		//alert($this.parent().children(".faculty_read_more").html());
	});

}

//confirm deleting profiles in your account
function confirmDel() {
	$('#account_pane .button_remove').live( 'click', function(e) {
    	e.preventDefault();
		$this = $(this);
		
		var del = confirm('By deleting this profile, you are removing this individual from your Account. You will no longer see any order history for this profile under previous orders.');
		
		if(del) {
			window.location = e.currentTarget.href;
		}
		//alert(e.currentTarget.href);
    });  

}



/*
 * bootstrap
 */
function init() {
    addItemHandler();
    addTabHandler();
    addBreadcrumbHandler();
    addTooltipHandler();
    addAttendeeHandler();
    initOverlay();
    addOverlay();
    bindNavHover();
    preloadImages();
    checkForCartItems();
    sendToFriend();
    facultyBios();
    confirmDel();
}

$(document).ready(function() {
    init();
});


//break tabs out of dom ready state, to avoid overflowing IEs JS handlers
$(window).load(function () {
	
});



