var path = "/app/webroot/js/uploadify";
var viewpath = "/js/uploadify/";
var imageFolderPath = "/img/";
			        
			        
function trimStartEndSelect(string)
{
	start = '<select>';
	end = '</select>';
	if(string.match("^"+start)==start)
	{
		string = string.replace(new RegExp("^"+start,"i"),'');
	}
	if(string.match(end+"$")==end)
	{
		string = string.replace(new RegExp(end+"$","i"),'');
	}
	return string;
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'

    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}

// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr, sep){
	var dtCh = sep;
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	//var strMonth=dtStr.substring(0,pos1)
	//var strDay=dtStr.substring(pos1+1,pos2)
	//var strYear=dtStr.substring(pos2+1)
	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function confirmDelete()
{
// class exists
	if($('.confirm_delete').length) {
		// add click handler
		$('.confirm_delete').click(function(){
			// ask for confirmation
			var result = confirm('Are you sure you want to delete this?');

			// show loading image
			$('.ajax_loader').show();
			$('#flashMessage').fadeOut();

			// get parent row
			var row = $(this).parent('div');

			// do ajax request
			if(result) {
				$.ajax({
					type:"POST",
					url:$(this).attr('href'),
					data:"ajax=1",
					dataType: "json",
					success:function(response){
						// hide loading image
						$('.ajax_loader').hide();

						// hide table row on success
						if(response.success == true) {
							row.fadeOut().remove();
						}

						// show respsonse message
						if( response.msg ) {
							$('#ajax_msg').html( response.msg ).show();
						} else {
							$('#ajax_msg').html( "<p id='flashMessage' class='flash_bad'>An unexpected error has occured, please refresh and try again</p>" ).show();
						}
					}
				});
			}
		return false;
		});
	}
}

function uploadyfier(toup)
{
	$(toup).uploadify({
		'uploader': path + '/uploadify.swf',
		'script': path + '/uploadify.php',
		'folder': path + upldi,
		'cancelImg': path + '/cancel.png',
		'fileExt':"*.jpg",
		'fileDesc':"Image files",
		'auto':true,
		'multi':true,
		'sizeLimit'   : 1100000,
		'onComplete': function(event, queueID, fileObj, response, data) {
			//alert(path + '/files'+"/"+fileObj.name);
			$("#images").append("<div><img alt='"+viewpath + "files/"+thispath+"/thumbs/"+response+"' src='"+viewpath + "files/"+thispath+"/thumbs/"+response+"'/> <input type='hidden' name='data["+thismod+"]["+index+"][filename]' value='"+response+"' /> <input type='hidden' name='data["+thismod+"]["+index+"][name]' value='"+response+"' /> <img alt='Delete' onClick='$(this).parent().remove()' src='"+imageFolderPath +"TrashIcon.jpg'/></div>");
			index = index + 1;
		},

		'onError': function(event, queueID, fileObj, errorObj) {
			//alert(errorObj.info);
		}
	});
}

function uploadyfiersingle(toup)
{
	$(toup).uploadify({
		'uploader': path + '/uploadify.swf',
		'script': path + '/uploadify.php',
		'folder': path + upldi,
		'cancelImg': path + '/cancel.png',
		'fileExt':"*.jpg",
		'fileDesc':"Image files",
		'auto':true,
		'sizeLimit'   : 1100000,
		'onComplete': function(event, queueID, fileObj, response, data) {
			//alert(path + '/files'+"/"+fileObj.name);
			$("#images").append("<div><img alt='"+viewpath + "files/"+thispath+"/thumbs/"+response+"' src='"+viewpath + "files/"+thispath+"/thumbs/"+response+"'/> <input type='hidden' name='data["+thismod+"][filename]' value='"+response+"' /> <input type='hidden' name='data["+thismod+"][name]' value='"+response+"' /> <img alt='Delete' onClick='$(this).parent().remove()' src='"+imageFolderPath +"TrashIcon.jpg'/></div>");
			index = index + 1;
		},

		'onError': function(event, queueID, fileObj, errorObj) {
			//alert(errorObj.info);
		}
	});
}
