$(document).ready(function() {
   
   $("[rel=auto]").each(function(i){
					 
		var mytab = $(this).attr('mytable');			 
    	$(this).autocomplete(GLOBAL_PATH+"/index.php?main=ajax_auto&process=com_ajax", 
								 { 
								 minChars:2, 
								 autoFill:false,
								 selectFirst:false,
								 maxItemsToShow:10,
								 extraParams: { 
								 				'table': mytab 
											  }
								 }); 
   });
	

light_settings = {
imageLoading:			GLOBAL_PATH+'/images/lightbox/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
imageBtnPrev:			GLOBAL_PATH+'/images/lightbox/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
imageBtnNext:			GLOBAL_PATH+'/images/lightbox/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
imageBtnClose:			GLOBAL_PATH+'/images/lightbox/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
imageBlank:				GLOBAL_PATH+'/images/lightbox/lightbox-blank.gif'
}
$('a.lightbox').lightBox(light_settings); 

});

function showhide(elemid) {
	$(elemid).slideToggle();
}
function showhidesec(elemid) {
	$("[relsh="+elemid+"]").slideToggle();
}

function warn() {
	if(confirm("Are you sure you want to delete the selected product?")) 
	return true;
	else
	return false;
}
function warn2(elem) {
	if(confirm(elem)) 
	return true;
	else
	return false;
}

function LimitAttach(myvar) {
	var file = $(myvar).val();
	extArray = new Array(".gif", ".jpg", ".jpeg", ".png");
	allowSubmit = false;
	if (!file) return false;
	ext = file.slice(file.lastIndexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}
	
	if(allowSubmit==false) {
	alert('Please select the image file with .gif, .jpg, .jpeg, .png extension');		
	$(myvar).val('');
	}
		
	//alert(allowSubmit);
}
function LimitAttachAll(myvar) {
	var file = $(myvar).val();
	extArray = new Array(".gif", ".jpg", ".jpeg", ".png", ".doc", ".docx", ".pdf", ".zip");
	allowSubmit = false;
	if (!file) return false;
	ext = file.slice(file.lastIndexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}
	
	if(allowSubmit==false) {
	alert('Please select the file with .gif, .jpg, .jpeg, .png, .doc, .docx, .pdf, .zip extension');		
	$(myvar).val('');
	}
		
	//alert(allowSubmit);
}
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function in_array (needle, haystack) {
	 var key = '';
	 
	  for (key in haystack) {
		  if (haystack[key] == needle) {
			  return true;
		  }
	  }
	  
	  return false;
}

function duplicateRow(strTableName,maxRows) {
		 
		 
		 if (maxRows!="" && $( "#" + strTableName + " .detailsTr" ).length >= maxRows ){
		 alert('You cannot add more than '+maxRows+' rows!');
		 return false;
		 }
		
        // First, lets create the new row using the last one as template...
        var clonedRow = $( "#" + strTableName).children('tbody').children('tr:last').clone();
        // Take the current identifier, some number in the first cell of the row
        intCurrentRowId = parseInt( $( "#numberIdentifier:last",clonedRow ).val() );
        // Set the new ID
        intNewRowId = intCurrentRowId + 1;
		
		//console.log($( "#" + strTableName).children('tbody').children('tr:last').html());
        
		// Change the current identifier of the row to the new one
        $( "#numberIdentifier:last", clonedRow ).val( intNewRowId );

        // Now let's create the Delete link using the ID of the new TR
        $( "#delete_link"+ intCurrentRowId , clonedRow ).attr( "onClick", "deleteRow( '"+ strTableName +"', 'detailsTr"+ intNewRowId +"' )" );
        
        
		// Change the Id / Name or anything you want for the new attribs...here is where you need to add a lot of stuff to change the id of your variables

        // The following code works without problems on Firefox or IE7
		
		$( "#files"+ intCurrentRowId , clonedRow ).attr( { "id" : "files" + intNewRowId, "name" : "files" + intNewRowId, "value" : "" } );    
				
		$( "input[type=text], textarea", clonedRow ).each(function(){
												
												id_name = stringFilter($(this).attr('id'));
												$(this).attr( { "id" : id_name + intNewRowId, "value" : "" } );										
											   
												});
		
		$( "select", clonedRow ).each(function(){
												
												id_name = stringFilter($(this).attr('id'));
												$(this).attr( { "id" : id_name + intNewRowId} );										
											   	$(this).find('option:selected').attr('selected',false);
												
												});
		
		
		$( ".map1" , clonedRow ).hide();
		$( "#mapbutton" , clonedRow ).attr("onClick", "mymapfunc("+intNewRowId+",'"+strTableName+"')");
		$( "#geoloc_lat, #geoloc_lon" , clonedRow ).html("");
		$( "#lat"+ intCurrentRowId , clonedRow ).attr({ "id" : "lat" + intNewRowId, "value" : "" });
		$( "#lon"+ intCurrentRowId , clonedRow ).attr({ "id" : "lon" + intNewRowId, "value" : "" });

						
		$( "#delete_link"+ intCurrentRowId , clonedRow ).attr( { "id" : "delete_link" + intNewRowId } );
        $( "#delete_link"+ intNewRowId , clonedRow ).css( { "display" : "" } );
       
				
        // Add to the new row to the original table
        $( "#" + strTableName ).append( clonedRow );
         
       // $( "#" + strTableName ).append( clonedRow );
        // And finally change the ID of the last row to something we can delete later, not sure why can not be done before the append :S
        $( "#" + strTableName).children('tbody').children('tr:last').attr( "id", "detailsTr" + intNewRowId );

		$focus_elem=$("[type='text']", clonedRow)[0];
		if($focus_elem)
		$focus_elem.focus();
		
}

function deleteRow( strTableName, strId )
{
    if ( $( "#" + strTableName + " .detailsTr" ).length > 1 )
    {
        $( "#" + strTableName + " #" + strId ).remove();
    }
    else
    {
        alert( 'You have to keep at least 1 row!' );
    }

}
function deleteLastRow( strTableName )
{
    if ( $( "#" + strTableName + " .detailsTr" ).length > 1 )
    {	
	    $( "#" + strTableName + " .detailsTr:last").remove();
    }
    else
    {
        alert( 'You have to keep at least 1 row!' );
    }

}
function stringFilter (input,filter) {
	
	s = input;
	
	if(filter!=undefined)
	filteredValues = filter
	else
	filteredValues = "1234567890";     // Characters stripped out
		
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
	var c = s.charAt(i);
	if (filteredValues.indexOf(c) == -1) returnString += c;
	}

	return returnString;
}

function ajax_del_image(from) {
	if(!confirm('Are you sure you want to delete this image'))
	return false;
	//to   = '#icontent3 span';
	$.get(GLOBAL_PATH+'/index.php?main=ajax&sub=ajax_img&process=com_ajax', {  'img_id' : $(from).attr('img_id') }, 
	function (data){
		if(data==1) {
			$('#imgtable_'+$(from).attr('img_id')).fadeOut("slow");
		}else{
			alert('Error in deleting the specific image');
		}
	})
}

function update_box(box_id,url) {
	$(box_id).html('<img src="'+IMAGE_PATH+'/icons/ajax_loading.gif" width="16" height="16">');
	$.get(url, '', 
	function (data){
		if(data!="") {
			$(box_id).html(data);
		}else{
			alert('Error in updating the '+box_id+' box');
		}
	})
}

function mytab(tab_id, onclass) {
	
	$('.mybox').css('display','none');
	$('.mytab').parent().removeClass(onclass);
	//onclass = $().attr('onclass');
	$('#mybox'+tab_id).css('display','');
	$('#mytab'+tab_id).parent().addClass(onclass);
			
}

function change_select(from, target) {
	
	$.get('index.php?main=ajax&sub=ajax_makers&process=com_ajax',{ makers_id : $(from).val() },
	  function update_select(data, status) {
	  $(target).html(data);
	  }
	);
}

function update_customers_packages(from, target) {
	
	$.get('index.php?main=ajax&sub=ajax_customers_packages&process=com_ajax',{ customers_id : $(from).val() },
	  function update_select(data, status) {
	  $(target).html(data);
	  }
	);
}


function mymapfunc(myvar,table){
		
		if($('#mapbutton', '#'+table+' #detailsTr'+myvar).attr('rel')=='1') {
			
			$('#mapbutton', '#'+table+' #detailsTr'+myvar).attr('rel','2');
			var myadd = "";
			
			//console.log($('#baddress1_id OPTION:selected'));
			//clearDefaultText();
			
			/*if ($('#bcity').val()!="") {
			myadd+= $('#bcity').val()+',';
			} 
			
			if($('#bstate_id OPTION:selected').val()!=''){
			var bstate = $('#bstate_id OPTION:selected').text();
			}else{
			var bstate = $('#bstate').val();	
			}
			if (bstate!="") {
			myadd+=bstate+',';
			} 
			
			if($('#bcountry_id OPTION:selected').val()!=''){
			var bcountry = $('#bcountry_id OPTION:selected').text();
			}else{
			var bcountry = $('#bcountry').val();	
			}
			if(bcountry!=''){
			myadd+= bcountry+',';
			} 
			
			
			
			myadd = myadd.substr(0,myadd.length-1);
			*/	
			//$('#maplocation', '#detailsTr'+myvar).val(myadd);		
		}
				
		//$('#mapframe').attr('src','../index.php?main=map&sub=index&process=1&address='+$('#maplocation').val()+'&cname='+$('#bcompany_name').val());
		var add   = $('#maplocation'+myvar, '#'+table+' #detailsTr'+myvar).val();
		var cname = $('#bcompany_name', '#'+table+' #detailsTr'+myvar).val();
		//$.getScript(url, { 'address' : $('#maplocation').val() , 'cname' : $('#bcompany_name').val() },function (data){ $('#mapframe').html(data);})
		//window.frames[iframename].document.getElementId('myfield1ID').value
		//console.log($('#maplocation'+myvar, '#'+table+' #detailsTr'+myvar));
		if($.trim(add)=='')
		{
		alert('Please enter the map address');
		$('#maplocation'+myvar, '#'+table+' #detailsTr'+myvar).focus();
		return false;
		}
		
		$('.map1', '#'+table+' #detailsTr'+myvar).show();
		
		
		$('#mapframe', '#'+table+' #detailsTr'+myvar).contents().find('#address').val(add);
		$('#mapframe', '#'+table+' #detailsTr'+myvar).contents().find('#cname').val(cname);
		$('#mapframe', '#'+table+' #detailsTr'+myvar).contents().find('#row_ele').val(myvar);
		$('#mapframe', '#'+table+' #detailsTr'+myvar).contents().find('#mapform').submit();
				
		//$('#mapbutton', '#detailsTr'+myvar).val('Search Map Again');
	
}

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "mm/dd/yyyy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
