//---------------------------------------- Windows ----------------------------------------
/*
	Attaches the onclick behavior to elements with specific class names.  The dimensions of the window depend on the class name.
	
	Parameters:
	Name	Type			Default		Description
	parent	object						(Optional) Object to initialize child elements.
	
	Returns:
	Type	Description
	void
*/
function initWindows(parent) {
	if(parent) {
		var popup_small = dojo.query(".LinkPopupSmall", parent);
		var popup_medium = dojo.query(".LinkPopupMedium", parent);
		var popup_large = dojo.query(".LinkPopupLarge", parent);
		var new_window = dojo.query(".LinkNewWindow", parent);
	} else {
		var popup_small = dojo.query(".LinkPopupSmall");
		var popup_medium = dojo.query(".LinkPopupMedium");
		var popup_large = dojo.query(".LinkPopupLarge");
		var new_window = dojo.query(".LinkNewWindow");
	}
	
	//LinkPopupSmall
	dojo.forEach(popup_small, function (result) {
		dojo.connect(result, "onclick", function (e) {openWindow(e.currentTarget.href, "small"); e.preventDefault();});
	});
	
	//LinkPopupMedium
	dojo.forEach(popup_medium, function (result) {
		dojo.connect(result, "onclick", function (e) {openWindow(e.currentTarget.href, "medium"); e.preventDefault();});
	});
	
	//LinkPopupMedium
	dojo.forEach(popup_large, function (result) {
		dojo.connect(result, "onclick", function (e) {openWindow(e.currentTarget.href, "large"); e.preventDefault();});
	});
	
	//LinkNewWindow
	dojo.forEach(new_window, function (result) {
		dojo.connect(result, "onclick", function (e) {openWindow(e.currentTarget.href, "new"); e.preventDefault();});
	});
}

/*
	Opens a new browser window with dimensions based on "type."  Custom dimensions may be used if "type" is an object containing width and height parameters.
	
	Parameters:
	Name	Type			Default		Description
	url		string						The URL location
	type	string/object				A string containing the class name, or an object containing specific width and height
	name	string						The name to assign to the window
	
	Returns:
	Type	Description
	void
*/
function openWindow(url, type, name) {
	if(!name) {
		name = "";
	}
	
	if(type && type.width && type.height) {
		window.open(url, name, "width=" + type.width + ", height=" + type.height + ", scrollbars, resizable");
	} else if(type) {
		var width = 800;
		var height = 600;
		switch(type) {
			case "small":
				width = 320;
				height = 240;
				break;
			case "medium":
				width = 640;
				height = 480;
				break;
			case "large":
				width = 800;
				height = 600;
				break;
		}
		if(type == "new") {
			var viewport = getViewport();
			var mod_width = Math.round(viewport.w * 0.8);
			var mod_height = Math.round(viewport.h * 0.8);
			window.open(url, name, "width=" + mod_width + ", height=" + mod_height + ", scrollbars, resizable, menubar, toolbar, location, status");
		} else {
			window.open(url, name, "width=" + width + ", height=" + height + ", scrollbars, resizable");
		}
	} else {
		window.open(url, name);
	}
}

//Return the width and height of the viewport
function getViewport() {
	var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	return {w: width, h: height};
}

//Request error handler.
function dataError(response, ioArgs) {
	console.error("HTTP status code: ", ioArgs.xhr.status);
	return response;
}

function initBroadcast() {
	var featured = dojo.byId("Featured");
	if(featured && dojo.byId("Home")) {
		dojo.xhrGet({
			url: "apps/video/broadcast.cfml",
			load: broadcastCallback,
			preventCache: true,
			error: dataError
		});
	}
	
	var broadcast_notice = dojo.byId("Broadcast");
	if(broadcast_notice) {
		dojo.xhrGet({
			url: "apps/video/broadcast.cfml?notice",
			load: broadcastNoticeCallback,
			preventCache: true,
			error: dataError
		});
	}
}

function broadcastNoticeCallback(response, ioArgs) {
	if(response.length > 0 && response != "false") {
		var broadcast_notice = dojo.byId("Broadcast");
		broadcast_notice.innerHTML = response;
		initLinks(broadcast_notice);
	}
	return response;
}

function broadcastCallback(response, ioArgs) {
	if(response.length > 0 && response != "false") {
		var featured = dojo.byId("Featured");
		featured.innerHTML = response;
		initLinks(featured);
		initVideoPlayer(dojo.byId("VideoBroadcast"), dojo.byId("VideoBroadcastInfo").value, true);
	}
	return response;
}

function initVideoEmbed() {
	var embed = dojo.query(".VideoEmbed");
	dojo.forEach(embed, function (result) {
		var id = result.id.split("VideoEmbed")[1];
		var path = "/apps/video/video_embed.cfml?id=" + id;
		
		if(document.location.href.indexOf("STAGE-SNWA2") != -1) {
			path = "/STAGE-SNWA2" + path;
		}
		
		dojo.xhrGet({
			url: path,
			load: function (response, ioArgs) {
				if(response.length > 0) {
					videoEmbedCallback(response, ioArgs, result, id);
				}
				return response;
			},
			error: dataError
		});
	});
}

function videoEmbedCallback(response, ioArgs, object, id) {
	var video_embed = dojo.byId("VideoEmbed" + id);
	video_embed.innerHTML = response;
	
	var path = dojo.byId("VideoEmbedInfo" + id).value;
	initVideoPlayer(object, path);
}

function initVideoPlayer(object, path, broadcast) {
	var swf_path = "/apps/video/swf/player.swf";
	if(document.location.href.indexOf("STAGE-SNWA2") != -1) {
		swf_path = "/STAGE-SNWA2" + swf_path;
	}
	
	if(!broadcast) {
		var cid = path.split("cid=")[1].split("&")[0];
		
		var flashvars = {
			id: object.id,
			link: "javascript: openVideo('" + cid + "', '" + object.id + "');",
			linktarget: "_top"
		};
	} else {
		var flashvars = {
			id: object.id,
			link: "javascript: openBroadcast('" + object.id +"');",
			linktarget: "_top"
		};
	}
	var params = {
		allowscriptaccess: "always",
		allowfullscreen: "true",
		wmode: "opaque",
		flashvars: path,
		id: object.id
	};
	var attributes = {
		styleclass: "VideoEmbed",
		id: object.id
	};
	swfobject.embedSWF(swf_path, object.id, "100", "100", "10", false, flashvars, params, attributes);
	
	var flash_link = dojo.query("a", object)[0];
	if(flash_link) {
		dojo.connect(flash_link, "onclick", function (e) {
			openWindow(e.currentTarget.href, "new");
			e.preventDefault();
		});
	}
}

function openBroadcast(video_id) {
	var href = "apps/video/broadcast_view.cfml";
	
	if(document.location.href.indexOf("REDESIGN") != -1) {
		href = "/REDESIGN/" + href;
	}
	
	dojo.byId(video_id).sendEvent("STOP", null);
	openWindow(href, {width: 575, height: 352});
}

function openVideo(category_id, video_id) {
	var id = video_id.split("VideoEmbed")[1];
	var href = "/apps/video/index.cfml?cid=" + category_id +"&vid=" + id + "&autostart";
	
	if(document.location.href.indexOf("STAGE-SNWA2") != -1) {
		href = "/STAGE-SNWA2" + href;
	}
	
	dojo.byId(video_id).sendEvent("STOP", null);
	openWindow(href, "large");
}

function playerReady(obj) {
	var player = dojo.byId(obj.id);
	player.addModelListener("STATE", "function (obj) {if(obj.newstate == \"COMPLETED\") {dojo.byId(\"" + player.id + "\").sendEvent(\"STOP\");}}");
}

function initStriping() {
	var stripe = dojo.query(".Stripe");
	dojo.forEach(stripe, function (result) {
		var rows = result.getElementsByTagName("tr"); 
		dojo.forEach(rows, function (result, index) {
			if(index % 2 != 1) {
				dojo.addClass(result, "StripeColor");
			}
		});
	});
}

//Initialize link behavior based on class names or href.
function initLinks(parent) {
	var site_domain = "snwa.com";
	var certificate_domain = "digicert.com";
	
	var anchor_links = [];
	
	if(parent) {
		anchor_links = dojo.query("a", parent).concat(dojo.query("area", parent));
	} else {
		anchor_links = dojo.query("a").concat(dojo.query("area"));
	}
	
	dojo.forEach(anchor_links, function (result) {
		if(result.href.indexOf("javascript:") == -1 && !dojo.isDescendant(result, dojo.byId("cf-container"))) {
			var behavior = false;
			
			//Normalize hrefs for secure page
			if(document.location.href.indexOf("https://") == 0) {
				if(result.href.indexOf("secure=true") == -1 && result.href.indexOf("#") == -1) {
					var current_anchor_text = result.innerHTML;
					result.href = result.href.replace("https://", "http://");
					result.innerHTML = current_anchor_text;
				}
			}
			
			if(dojo.hasClass(result, "HoverPopup")) {
				dojo.connect(result, "onmouseover", "showPopup");
				dojo.connect(result, "onmouseout", "hidePopup");
			}
			
			//Video portal
			if(!behavior && result.href.indexOf("apps/video/") != -1) {
				dojo.addClass(result, "LinkVideo");
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "large");
					e.preventDefault();
				});
				behavior = true;
			}
			
			//Photo gallery
			if(!behavior && result.href.indexOf("apps/photo/") != -1) {
				dojo.addClass(result, "LinkPhoto");
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "large");
					e.preventDefault();
				});
				behavior = true;
			}
			
			//Contact
			if(result.href.indexOf("apps/contact/") != -1) {
				dojo.addClass(result, "LinkEmail");
			}
			
			//Subscription
			if(result.href.indexOf("apps/subscription/index.cfml") != -1) {
				dojo.addClass(result, "LinkSubscribe");
			}

			//Watering Group
			if(result.href.indexOf("apps/watering_group") != -1) {
				behavior = true;
			}
			
			//Pop-up windows
			if(!behavior && dojo.hasClass(result, "LinkPopupSmall")) {
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "small");
					e.preventDefault();
				});
				behavior = true;
			}
			if(!behavior && dojo.hasClass(result, "LinkPopupMedium")) {
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "medium");
					e.preventDefault();
				});
				behavior = true;
			}
			if(!behavior && dojo.hasClass(result, "LinkPopupLarge")) {
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "large");
					e.preventDefault();
				});
				behavior = true;
			}
			if(!behavior && dojo.hasClass(result, "LinkNewWindow")) {
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "new");
					e.preventDefault();
				});
				behavior = true;
			}
			
			//Links
			var ext_pdf = ".pdf";
			if(result.href.indexOf(ext_pdf) != -1) {
				dojo.addClass(result, "LinkPDF");
			}
			
			var ext_doc = ".doc";
			if(result.href.indexOf(ext_doc) != -1) {
				dojo.addClass(result, "LinkDOC");
			}
			
			var ext_xls = ".xls";
			if(result.href.indexOf(ext_xls) != -1) {
				dojo.addClass(result, "LinkXLS");
			}
			
			var ext_jpg = ".jpg";
			if(result.href.indexOf(ext_jpg) != -1) {
				dojo.addClass(result, "LinkImage");
			}
			
			var ext_gif = ".gif";
			if(result.href.indexOf(ext_gif) != -1) {
				dojo.addClass(result, "LinkImage");
			}
			
			var ext_png = ".png";
			if(result.href.indexOf(ext_png) != -1) {
				dojo.addClass(result, "LinkImage");
			}
			
			var ext_zip = ".zip";
			if(result.href.indexOf(ext_zip) != -1) {
				dojo.addClass(result, "LinkArchive");
			}
			
			if(!behavior && ((result.href.indexOf(site_domain) == -1 && result.href.length > 0 && result.href.indexOf(certificate_domain) == -1) || dojo.hasClass(result, "LinkExternal"))) {
				dojo.addClass(result, "LinkExternal");
				dojo.connect(result, "onclick", function (e) {
					openWindow(e.currentTarget.href, "new");
					e.preventDefault();
				});
			}
		}
	});
	
	// Remove any classes from search pagination
	dojo.query(".Pagination a").forEach(function (result) {
		result.className = null;
	});
}

//Initialize close and print buttons for pop-up windows
function initPopup() {
	var popup_close = dojo.query(".PopupClose");
	dojo.forEach(popup_close, function (result) {
		dojo.connect(result, "onclick", function (e) {
			top.close();
			e.preventDefault();
		});
	});
	
	var popup_print = dojo.byId("PopupPrint");
	if(popup_print) {
		dojo.connect(popup_print, "onclick", function (e) {
			window.print();
			e.preventDefault();
		});
	}
}

//Initialize Dojo widgets
function initWidgets() {
	dojo.require("dojo.parser");
	dojo.addOnLoad(function () {dojo.parser.parse();});
	
	dojo.require("custom.Date");
	dojo.addOnLoad(initDatePicker);
}

//Initialize helper text behavior for date widgets
function initDatePicker() {
	dojo.query(".FormDateSelector input.dijitInputInner").forEach(function (date) {
		if(date.value == "") {
			dojo.addClass(date, "Default");
			dojo.connect(date, "onclick", function (e) {
				if(date.value == "mm/dd/yyyy") {
					dojo.removeClass(date, "Default");
					date.value = "";
				}
			});
			dojo.connect(date, "onfocus", function (e) {
				if(dojo.hasClass(date, "Default")) {
					dojo.removeClass(date, "Default");
					date.value = "";
				}
			});
			date.value = "mm/dd/yyyy";
		}
	});
}

// Start of Watering Group Functions.
//

function get_watering_group_path() {
  var wg_path = "/apps/watering_group";

  if(document.location.href.indexOf("STAGE-SNWA2") != -1) 
	wg_path = "/STAGE-SNWA2" + wg_path;
  else if(document.location.href.indexOf("STAGE-SNWA") != -1) 
	wg_path = "/STAGE-SNWA" + wg_path;
  else if(document.location.href.indexOf("local2/matt") != -1) 
	wg_path = "/local2/matt/snwa/root" + wg_path;
	
  return wg_path;  
}

function setWGLinkEvents() {
  if ( dojo.byId("WGSubmit") ) 
    dojo.connect( dojo.byId("WGSubmit"), "onclick", "getWateringGroup" ); 

  if ( dojo.byId("WGSearchAgain") )
    dojo.connect( dojo.byId("WGSearchAgain"), "onclick", "searchAgainWateringGroup" ); 

  WGExternalLinks = dojo.query(".LinkExternal", dojo.byId("WateringGroup")); 

  dojo.forEach(WGExternalLinks, function (result) {
	dojo.connect(result, "onclick", function (e) {openWindow(e.currentTarget.href, "new"); e.preventDefault();});
  });

}
	

function populateWateringGroup(){
	var box = dojo.byId("WateringGroup");
	if(box) {
		dojo.xhrGet({
			url: get_watering_group_path() + "/wg_form.cfml",
			load: populateWateringGroupCallback,
			preventCache: true,
			error: dataError
		});
	}
}

function searchAgainWateringGroup(e){
	var box = dojo.byId("WateringGroup");
	if(box) {
		dojo.xhrPost({
			url: get_watering_group_path() + "/wg_form.cfml?another=",
			load: populateWateringGroupCallback,
			preventCache: true,
			error: dataError
		});
	}
    e.preventDefault();
}

function populateWateringGroupCallback(response, ioArgs) {
	if(response.length > 0) {
	    dojo.byId("WateringGroup").innerHTML=response;	
	    setWGLinkEvents();  
	}
}

function getWateringGroup(e) {
  dojo.xhrPost ({
     url: get_watering_group_path() + "/get_wg_data.cfml",
     form: "WGForm",
     load: showWateringGroupResult
  });
  e.preventDefault();
}

function showWateringGroupResult(response, ioArgs) {
/*
	Some errors go to the results page, see process_errors.cfml
*/
	  if ( response.indexOf("^error^") != -1 ) {
	    location.href=get_watering_group_path() + "/results.cfml";
	  }
	  else {
	    dojo.byId("WateringGroup").innerHTML=response;	
	    setWGLinkEvents();  
	  }	
}

//
// End of Watering Group Functions.
//


function initSite() {
	initStriping();
	initLinks();
	initVideoEmbed();
	initBroadcast();
	initPopup();
	populateWateringGroup();
}

dojo.addOnLoad(initSite);

