// JavaScript Document
if (!nmb) { var nmb = {}; }

nmb.premium = function() {

	// object shortcuts
	var yui_util = YAHOO.util;
	var yui_Event = YAHOO.util.Event;
	var yui_Dom = YAHOO.util.Dom;
	
	// the yui dialog
	var pc_dialog;
	var pc_wait;

	function showPremium(a) {
		
		// put the file href into the p_file form element
		var pc_file = document.getElementById('pc_file');
		pc_file.value = a.href;
		
		// put the title or href into #document-name
		var name = document.getElementById('document-name');
		if (a.title) {
			name.innerHTML = a.title;
		} else {
			var paths = a.href.split(/\//g);
			name.innerHTML = paths[paths.length];
		}
			
		var handleCancel = function() {
			this.cancel();
		}

		if (!pc_dialog) {
			// Instantiate the Dialog
			pc_dialog = new YAHOO.widget.Dialog(
					"dialogPremium", 
					{ 
						postmethod: 'form',
						width : '609px',
						fixedcenter : true,
						visible : false,
						draggable : false,
						modal : true,
						close : false,
						underlay : 'none',
						constraintoviewport : true,
						zIndex : 1000
					}
			);

			// set up required field validation
			pc_dialog.validate = function() {
				var data = this.getData();
	
				var error_message = "The fields marked with an * are required in order to download premium content.";
	
				// make sure the fields were expecting exist.  if they dont form fields might have
				// been renamed and it will cause the form to submit w/o required data
				if (typeof(data.form_name) == "undefined" ||
					typeof(data.form_email) == "undefined" ||
					typeof(data.form_contact_me) == "undefined" ||
					typeof(data.form_product) == "undefined") {
					alert("Form configuration error");
					return false;
				}
				
				// name and email are required fields
				if (data.form_name == "" || data.form_email == "") {
					alert(error_message);
					return false;
					
				// if contact me checked, product is a required field
				} else if (data.form_contact_me && data.form_product == "") {
					alert(error_message);
					return false;
				}
				
				var days = 200;
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				YAHOO.util.Cookie.set("premiere", data.form_email, { domain: "nmbtc.com", path: "/", expires: date });
				YAHOO.util.Cookie.set("premiere", data.form_email, { domain: "nmbtech.com", path: "/", expires: date });
				
				// log the submit
				pageTracker._trackPageview('/premium/submit');
				
				// log the hit
				logHit(a.href);
				
				return true;
			};
			
			var e = document.getElementById('dialogPremiumClose');
			function fnCallback(e) { alert("click"); }
			YAHOO.util.Event.addListener( e, "click", function() { pc_dialog.cancel(); });

			// nmb.premium.pc_dialog.cancel();

		}
		

		// Render the Dialog
		pc_dialog.render();
	
		pc_dialog.show();
		
		// log the display
		pageTracker._trackPageview('/premium/display');
		window.log("pageTracker._trackPageview('/premium/display');");
	}
	
	function loadPremium(a) {

		// if we've already created the Premium dialog
		if (pc_dialog) {

			// and show the Premium registration form
			showPremium(a);

		} else {
			// 
			if (!pc_wait) {
			
				// Initialize the temporary Panel to display while waiting for external content to load
				pc_wait = new YAHOO.widget.Panel(
						"panelWait",  
						{ width: "240px", 
						  fixedcenter: true, 
						  close: false, 
						  draggable: false, 
						  modal: true,
						  visible: false
						} 
				);
				
				pc_wait.setHeader("Loading, please wait...");
				pc_wait.setBody("<img src=\"/assets/scripts/premium/loading.gif\"/>");
				pc_wait.render(document.body);
				
			}
			
			// Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
			var callback = {
				success : function(o) {
					// make sure the loading popup is hidden
					pc_wait.hide();
					
					// display the form
					// create the dialog container
					var dialog = document.createElement('DIV');
					dialog.id = 'dialogPremium';
					dialog.innerHTML = '<div class="hd"><a id="dialogPremiumClose">close</a></div>' +
						               '<div class="bd" id="dialogPremiumContent">' + o.responseText + '</div>' + 
						               '<div class="ft"><a id="dialogPremiumPrivacy" href="/terms-and-conditions.html">privacy policy</a></div>';
					document.body.appendChild(dialog);

					// attach the contact me checkbox handler
					yui_Event.addListener(
							"pc_contact_me", 
							"click", 
							toggleContact
					);
					
					// and run it once to hide the contact area
					toggleContact();
					
					// and show the registration form
					showPremium(a);
				},
				failure : function(o) {
					alert("Connection Failed.");
					pc_wait.hide();
				}
			}
		
			// Show the Panel
			pc_wait.show();
			
			// Connect to our data source and load the data
			var conn = yui_util.Connect.asyncRequest("GET", "/assets/scripts/premium/premium_form.html?r=" + new Date().getTime(), callback);
		}
	}

	function toggleContact() {
		var check = document.getElementById('pc_contact_me');
		var expand = document.getElementById('pc_contact_expand');
		expand.style.display = check.checked ? '' : 'none';
		if (pc_dialog) { pc_dialog.center(); }
	}
	
	function disableContact() {
		var check = document.getElementById('pc_contact_me');
		var expand = document.getElementById('pc_contact_expand');
		
		var inputs = yui_Dom.getElementsBy(
			function(el) {
				return el.tagName.match(/INPUT|SELECT|BUTTON|TEXTAREA/gi);
			},
			'',
			'pc_contact_expand'
		);
		
		for (var i=0; i<inputs.length; i++) {
			inputs[i].disabled = (check.checked ? '' : 'disabled');
		}
	}
	
	var reg_premium = /\/pdf\/premiere\/(.*)$/i;

	// attach premium link handler
	function attachPremium() {
		// get links which point to /pdf/premiere/
		var links = yui_Dom.getElementsBy( 
			function(el) { 
				return reg_premium.test(el.href);
			}, 
			'a'
		);
		
		// attach click handler to links
		yui_Event.addListener(
			links,
			'click',
			function (evt) {
				var c = yui_util.Cookie.get("premiere");
				if (!c) {
					window.log('cookie not found');
					yui_Event.preventDefault(evt);
					loadPremium(this);
				} else {
					window.log('cookie found: ' + c);
					logHit(this.href);
				}
			}
		);
		window.log('premium attachment complete');
	}

	function logHit(href) {
		// capture filename (everything after /pdf/premiere/)
		var matches = reg_premium.exec(href);
		pageTracker._trackPageview('/premium/' + matches[1]);
		window.log("pageTracker._trackPageview('/premium/" + matches[1] + "');");
	}
	
 	attachPremium();
	return this;
}

// run when the DOM is done loading
YAHOO.util.Event.onDOMReady( nmb.premium );
