var assetBrowseTarget;
var assetBrowseWindow;

/**
 * Functions common to all files in the site
 */
function getURL(url) {
	window.location = url;
}

function openWindow(pageUrl,width,height,winName,scrollbars) {
	if(scrollbars != 1) scrollbars = 0;
    var newWindow = window.open(pageUrl,winName,"toolbar=0,scrollbars="+scrollbars+",location=0,statusbar=0,menubar=0,resizable=0,width="+width+",height="+height);
    return newWindow;
}

function openAssetUploadWindow() {
	openWindow("/assets/add",400,154);
	return false;
}

function openAssetBrowseWindow(element) {
	assetBrowseTarget = element;
	assetBrowseWindow = openWindow("/assets/browse",412,400,'browseWindow',1);
	return false;
}

function linkSelected(link) {
	$('#'+assetBrowseTarget)[0].value = link;
	$('#'+assetBrowseTarget).addClass("focus");
	if($('#'+assetBrowseTarget).hasClass("required")) {
		validateField($('#'+assetBrowseTarget),'required');
	}
	assetBrowseWindow.close();
}

function refreshForLogin() {
	assetBrowseWindow.close();
	window.location=window.location;
}

function randomUUID() {
  var s = [], itoh = '0123456789ABCDEF';
  for (var i = 0; i <36; i++) s[i] = Math.floor(Math.random()*0x10);
  s[14] = 4;  // Set 4 high bits of time_high field to version
  s[19] = (s[19] & 0x3) | 0x8;  // Specify 2 high bits of clock sequence
  for (var i = 0; i <36; i++) s[i] = itoh[s[i]];
  s[8] = s[13] = s[18] = s[23] = '-';
  return s.join('');
}

//Form validation functions
function validateField(field,type) {
	var message
	var validationFailed
	if (type == 'required' || type == 'all') {
		if(field.css("display") == "none") return true;
		var fieldLength;
		var updateEvent;
		if(field.hasClass("radiobuttongroup")) {
			fieldLength = 0;
			if(field.children("input:radio:checked").length > 0) {
				fieldLength = 1;
				updateEvent = 'click';
			}
		} else {
			switch(field.get(0).tagName) {
				case "DIV":
					fieldLength = field.html().replace("<br>", "").length;
					break;
				case "SELECT":
					fieldLength = field.val().length;
					updateEvent = 'change';
					break;
				default:
					fieldLength = field.val().length;
					updateEvent = 'keypress';
					break;
			}
		}
		if(!field.parents('.input').hasClass("validated") && fieldLength == 0) {
			field.parents('.input').addClass("validated");

			validatorID = 'validator-required-'+field.attr("id");
			if(field.attr("requiredValidationMessage")) {
				message = field.attr("requiredValidationMessage");
			} else {
				message = 'This field is required';
			}
			$("#validators").append("<div id='"+validatorID+"' class='validator-wrapper'><div class='validator'><div class='validator-left'><img src='/images/bg_validator_left.png'></div><div class='validator-inner'>"+message+"</div><div class='validator-right'><img src='/images/bg_validator_right.png'></div></div></div>");
			elementPosition = field.position();
			position = {top:Math.round(elementPosition.top-2),left:Math.round(elementPosition.left+field.parents('.input').width()+6)};
			$('#'+validatorID).css(position);
			$('#'+validatorID).prev().hide();
			$('#'+validatorID).prev().fadeIn(200);
			field.bind(updateEvent,function() {
				validateField($(this),'required');
			});
			
			validationFailed = true;
		} else {
			if(field.parents('.input').hasClass("validated") && fieldLength > 0) {
				field.parents('.input').removeClass("validated");
				validatorID = 'validator-required-'+field.attr("id");
				$('#'+validatorID).remove();
			}
		}
		
		if(field.val().length == 0) { return false; }
	}
	if (field.get(0).tagName == "TEXTAREA" && field.attr("maxlength")>0 && (type == 'maxlength' || type == 'all')) {
		var mlength=field.attr('maxlength');
		if(!field.parents('.input').hasClass("validated") && field.attr("value").length>mlength) { 
			validationFailed = true;
			field.parents('.input').addClass("validated");

			validatorID = 'validator-required-'+field.attr("id");
			message = 'This field has a maximum length of '+field.attr('maxlength')+' characters';
			$("#validators").append("<div id='"+validatorID+"' class='validator-wrapper'><div class='validator'><div class='validator-left'><img src='/images/bg_validator_left.png'></div><div class='validator-inner'>"+message+"</div><div class='validator-right'><img src='/images/bg_validator_right.png'></div></div></div>");
			elementPosition = field.position();
			position = {top:Math.round(elementPosition.top-2),left:Math.round(elementPosition.left+field.parents('.input').width()+6)};
			$('#'+validatorID).css(position);
			$('#'+validatorID).prev().hide();
			$('#'+validatorID).prev().fadeIn(200);
			return false;
		} else {
			if(field.parents('.input').hasClass("validated") && field.attr("value").length<=mlength) {
				field.parents('.input').removeClass("validated");
				validatorID = 'validator-required-'+field.attr("id");
				$('#'+validatorID).remove();
			}
		}
	}
	if(type=='password_match') {
		if($(".password").attr("value")!='' && $(".password-confirmation").attr("value")!='' && ($(".password").attr("value") != $(".password-confirmation").attr("value"))) {
			if(!$(".password").parents('.input').hasClass("validated")) {
				$(".password").parents('.input').addClass("validated");
				message = 'Password and Re-type Password don\'t match';
				$("#validators").append("<div id='"+validatorID+"' class='validator-wrapper'><div class='validator'><div class='validator-left'><img src='/images/bg_validator_left.png'></div><div class='validator-inner'>"+message+"</div><div class='validator-right'><img src='/images/bg_validator_right.png'></div></div></div>");
				elementPosition = field.position();
				position = {top:Math.round(elementPosition.top-2),left:Math.round(elementPosition.left+field.width()+8)};
				$('#'+validatorID).css(position);
				$('#'+validatorID).prev().hide();
				$('#'+validatorID).prev().fadeIn(200);
				$(".password").bind('keyup',function() {
					validateField($(this),'password_match');
				});
				$(".password-confirmation").bind('keyup',function() {
					validateField($(this),'password_match');
				});
				validationFailed = true;
			}
			return false;
		} else {
			if($(".password").parents('.input').hasClass("validated")) {
				$(".password").parents('.input').removeClass("validated");
				validatorID = 'validator-password-match-'+field.attr("id");
				$('#'+validatorID).remove();
			}
		}
	}
	return true;
}

function validateForm(form) {
	var validForm = true;
	var validateElements = form.find(".input .required");
	for(i=0;i<validateElements.length;i++) {
		if (!validateField($(validateElements[i]), 'all')) {
			validForm = false;
		}
	}
	if(!validForm) {
		window.scrollTo(0,0);
	}
	return validForm;
}

function isMaxLength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength)
}

//Document Ready Functions
$(document).ready(function() {
	$(".nicEdit-main").blur(function() {
		$(this).parents('.input').removeClass("highlight");
	});
	$(".nicEdit-main").focus(function() {
		$(this).parents('.input').addClass("highlight");
	});
	$('#search-input').focus(function() {
		this.value = '';
	});
	$('#search-input').blur(function() {
		if (this.value == '') {
			this.value = 'SEARCH BLOG';
		}
	});
	$('.list div.list-item:even').addClass("alt");
	$(".text-input").blur(function() {
		$(this).parents('.input').removeClass("highlight");
	});
	$(".text-input").focus(function() {
		$(this).parents('.input').addClass("highlight");
	});
	$(".select-input").focus(function() {
		$(this).parents('.input').addClass("highlight");
	});
	$(".required").blur(function() {
		$(this).unbind('keypress');
		//validateField($(this),'required');
	});
	$("select.required").change(function() {
		//validateField($(this),'required');
	});
	$(".radiobuttongroup").click(function() {
		if($(this).hasClass("required")) {
			//validateField($(this),'required');
		}
	});
	$(".password").blur(function() {
		$(".password").unbind('keyup');
		//validateField($(this),'password_match');
		//validateField($(this),'required');
	});
	$(".password-confirmation").blur(function() {
		$(".password-confirmation").unbind('keyup');
		//validateField($(this),'password_match');
		//validateField($(this),'required');
	});
	$("form.validate").submit(function(event) { 
		if(!validateForm($(this))) {
			event.preventDefault();
		}
	});
	$('.confirm-delete-post').click(function() {
		return confirm("Are you sure you want to delete this post?");
	});
	$('.asset-input').click(function() {
		//openAssetBrowseWindow(this.id);
		tinyBrowserPopUp('file',this.id);
	});
	$('#asset-link').click(function() {
		//openAssetBrowseWindow(this.id);
		tinyBrowserPopUp('file');
	});
	$('.asset-input').focus(function() {
		if(this.value == '') { $(this).removeClass("asset-input"); }
	});
	$('.asset-input').each(function() {
		if(this.value != '') { $(this).removeClass("asset-input"); }
		//$(this).after("&nbsp;[ <a href=\"#\" class=\"clear-asset-input\">clear value</a> ]");
		//$(this).next().click(function() {
		//	$(this).prev().val("");
		//});
	});
	$('.list-search-input').focus(function() {
		if(this.value == 'Search Blog Post Titles') { this.value == '' }
	});
	$('.list-search-input').blur(function() {
		if(this.value == '') { this.value == 'Search Blog Post Titles' }
	});
});