﻿/*
- - ( FILE INFO ) - - - - - - - - - - - - - - - - - - - - - - - - 
 Name:           protomatter.global.js
 Title:          General scripts run on all pages
 Author:         Colin Mc Mahon [Protomatter Web Solutions]
                 www.protomatter.co.uk
 Version:        1.0
 Updated:        20/06/2008
- - - - - - - -  - - - - - - - - - - - - - - - - - - - - - - - - - 
*/

var utils = {
	goUrl : function(url)
	{
		if (url == 'back') {
			history.go(-1);
		} else {
			document.location = url;
		}
	},
	OpenWindow : function(in_url, in_win_id, in_width, in_height, in_scroll_bars) {
		if (in_width ==="" || in_width === null) { in_width = 486; }
		if (in_height === "" || in_height === null) { in_height = 500; }
		var features ='directories=0,location=0,menubar=0,scrollbars=' + in_scroll_bars + ',status=0,toolbar=0,resizable=1,width=' + in_width + ',height=' + in_height + ',screenX=15,screenY=15,top=15,left=15';
		in_url = in_url.replace(/\s/,'%20');
		var wind=window.open (in_url, in_win_id, features);
		wind.focus();
	},
	trim : function (str) {
		var	str = str.replace(/^\s\s*/, ''),
			ws = /\s/,
			i = str.length;
		while (ws.test(str.charAt(--i)));
		return str.slice(0, i + 1);
	},
	GetParam : function(name, str) {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( str );
		if( results === null )
		{
			return "";
		}
		else
		{
			return results[1];
		}
	},
	GetQS : function(name) {
		return utils.GetParam(name, window.location.href);
	},
	setCookie : function(c_name,value,expiredays,path)
	{
		var exdate=new Date()
		exdate.setDate(exdate.getDate()+expiredays)
		document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
		((path) ? "; path=" + path : "");
	},
	getCookie : function(c_name)
	{
		if (document.cookie.length>0)
		{
			c_start=document.cookie.indexOf(c_name + "=")
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1 
				c_end=document.cookie.indexOf(";",c_start)
				if (c_end==-1) c_end=document.cookie.length
				return unescape(document.cookie.substring(c_start,c_end))
			} 
		}
		return ""
	}
};

jQuery.preloadImages = function()
{
    for(var i = 0; i<arguments.length; i++)
    {
        jQuery("<img>").attr("src", arguments[i]);
    }
};

var ProtoDialog = function(content, title, cssClass, buttons)
{
    $(content).dialog({ 
        modal: true,
        draggable: false,
        resizable: false,
        title: title,
        dialogClass: cssClass,
        height: 150,
        overlay: { opacity: 0.5, background: "black" },
        buttons: buttons
    });
};

var FormError = {
    init : function()
    {
        alert("There were errors with your form submission.\nPlease review the form and try again.");
    }
};

/* --------------------------------------------------
   Script checks for required class form elements and
   blocks form submission if blank
   Copyright (C) Colin Mc Mahon, Protomatter Web
   Solutions 2007
   -------------------------------------------------- */
var Checkform = {
	init : function(in_text) {
		$('form').each(function(){
			if(!$(this).hasClass("no-validation"))
			{
			    $(this).submit(function(evt){
				    var ok = true;
				    $(this).find('.required').each(function(){
					    var val = this.value;
					    var pdiv = $(this).parents('div').get(0);
					    if(pdiv.className == "markItUpContainer")
					    {
					        pdiv = $(this).parents('div').get(3);
					    }
					    if(val === '' || val == in_text || val == '-1') {
					    	ok = false;
					    	$(pdiv).addClass('field-error');
					    } else {
					    	$(pdiv).removeClass('field-error');
					    }
				    });
    
				    if(ok===false)
				    {
					    evt.preventDefault();
					    FormError.init();
				    }
				    else
				    {
				        $(this).find('input[type="submit"]').each(function(){
						    $(this).addClass("disabled").click(function(evt){
						    	evt.preventDefault();
						    });
					    });
				    }
			    });
            }
		});
	}
};

var HighlightFields = {
	init : function (in_fields, in_cmts) {
		$(function(){
			var fldAr = in_fields;
			var cmtAr = in_cmts;
			var parentDiv;
			var itemTitle;
			var itemLabel;
			for (var i=0; i<fldAr.length; i++) {
				if(fldAr[i] != '')
				{
					var tmpElem = fldAr[i];
					if (tmpElem.indexOf('file_')!=-1 || tmpElem.indexOf('img_')!=-1) {
						tmpElem = tmpElem.split("__");
						tmpElem = tmpElem[1];
					}
					parentDiv = $("#" + tmpElem).parents('div').get(0);
					$(parentDiv).addClass('field-error');
					if(cmtAr[i] !== "")
					{
						itemTitle = cmtAr[i];
					}
					else
					{
						itemTitle = "Error";
					}
					itemLabel = $(parentDiv).find("label, span.label").get(0);
					$(itemLabel).attr("title", itemTitle);
				}
			}
		});
	}
};

var Validate = {
	init : function(fields)
	{
		var valid = true;
		for (var i = 0; i < fields.length; i++) {
			var val = $("#" + fields[i]).val();
			var pdiv = $("#" + fields[i]).parents("div").get(0);
			if (val === "" || val == "-1")
			{
				valid = false;
				$(pdiv).addClass('field-error');
			}
			else
			{
				$(pdiv).removeClass('field-error');
			}
		}
		if (!valid)
		{
			FormError.init();
		}
		return valid;
	}
};

/* --------------------------------------------------
   Script highlights form rows and fieldsets on
   focus of a form element
   Copyright (C) Colin Mc Mahon, Protomatter Web
   Solutions 2007
   -------------------------------------------------- */
var FocusFields = {
	init : function() {
		if(!document.all)
		{
			$("form").each(function(){
				$(this).find(".textfield, textarea, select, input[@type='checkbox'], input[@type='radio']").each(function(){
					$(this).focus(function(){
						var pdiv = $(this).parents("div").get(0);
						if(!$(pdiv).hasClass('focus'))
						{
							$(pdiv).addClass('focus');
						}
					});
					
					$(this).blur(function(){
						var pdiv = $(this).parents("div").get(0);
						if($(pdiv).hasClass('focus'))
						{
							$(pdiv).removeClass('focus');
						}
					});
				});
			});
		}
	}
};

SetSavedMessage = function(msg)
{
	$('#system-message').remove();
	$("#secondary-navigation-wrapper").after(
		$("<div id=\"system-message\" class=\"positive\">" + msg + "</div>").oneTime(6000, function() {
			$(this).fadeOut();
		})
	);
};

SetAjaxMessage = function(msg)
{
	$('#system-message').remove();
	$("#secondary-navigation-wrapper").after("<div id=\"system-message\" class=\"loading\">" + msg + "</div>");
}

SetReloadSavedMessage = function(msg)
{
	utils.setCookie("msg", msg, 200, "/");
};

var Delete = {
    init : function()
    {
        $('.delete').click(function (e) {
            e.preventDefault();
            var lnkTarget = this.href;
            ProtoDialog('<div class="proto-dialog">Are you sure you want to delete this item.</div>',
            "Confirm Delete",
            "confirm-delete",
            { 
                "Ok": function() { 
                    window.location.href = lnkTarget;
                }, 
                "Cancel": function() { 
                    $(this).dialog("close"); 
                }
            });
        });
    }
};

var Confirm = {
    init : function()
    {
        $('.confirm').click(function (e) {
            e.preventDefault();
			var isForm;
			if($(this).is("input[type='submit'], button[type='submit']"))
			{
				// this is an attempted form submission, get a ref to the form
				isForm = true;
				var thisForm = $(this).parents("form").get(0);
			}
			else
			{
				isForm = false;
				var lnkTarget = this.href;
			}
            ProtoDialog('<div class="proto-dialog">Are you sure you want to continue.</div>',
            "Confirm Action",
            "confirm-delete",
            { 
                "Ok": function() { 
					if(isForm)
					{
						$(thisForm).submit();
					}
					else
					{
						window.location.href = lnkTarget;
					}
                },
                "Cancel": function() { 
                    $(this).dialog("close"); 
                }
            });
        });
    }
};

GenPass = {
	init : function(in_field)
	{
		$('#GenPass').click(function(){
		    $.get('/admin/ajax-handler.ashx?action=GenPass', function(data){
		        $('#' + in_field).val(data);
		    });
		});
	}
};

g_GlobalEvents = function() {
    Delete.init();
	Confirm.init();
    Checkform.init();
    FocusFields.init();
    $(".back").click(function(e){
	    e.preventDefault();
	    utils.goUrl("back");
	});
	
	$("select.pg-jump").change(function(){
		var url = window.location.pathname + $.query.set("pg", $(this).val()).toString();
		utils.goUrl(url);
	});
	//$('.date').datepicker({showOn: 'button', buttonImage: '/admin/core/assets/images/calendar.png', buttonImageOnly: true, dateFormat: 'dd/mm/yy'});
};

$(function(){g_GlobalEvents();});

