
var myWindowCloseElement = null;
var jswinLoginWindow = null;
var urlLoginCallBack = null;



function showLoginWindow(url){

	if(typeof(url)=='undefined'){
		url = document.location.href;
	}
	urlLoginCallBack = url;

	if(!jswinLoginWindow){
		jswinLoginWindow = new jsWin({width:300,height:180,modal:true});
	}
	
	
	
	
	jswinLoginWindow.setTitle("Login");
	jswinLoginWindow.setContent("<p style='color:red' id='ajaxLoginInfo'></p><table>	<tr>		<td>			<label>Email</label>		</td>		<td>			<input id='login_info' type='text' value='' name='login'/>		</td>	</tr>	<tr>		<td>			<label>Password</label>		</td>		<td>			<input id='password_info' type='password' value='' name='password'/>		</td>	</tr>		</table><button id='btnAjaxLoginSubmit' onclick='login()'>Login</button><br /><br /><a href='en/parent'>Create an account</a>");
	jswinLoginWindow.show();
	
}


function login(){
	
	if(!urlLoginCallBack){
		return false;
	}
	
	$('btnAjaxLoginSubmit').hide();
	
	
	var urlAjax = "http://www.thekidscoop.com/admin/form.php?action=useCustomClass&m=ajaxLogin&login="+$F('login_info')+"&password="+$F('password_info');
	
	var ar = new Ajax.Request(urlAjax, {});
	ar.options.onSuccess = function(origReq){
		console.warn(origReq.responseText);
		var json = origReq.responseText.evalJSON();
		if(json['login']=='success'){
			document.location.href=urlLoginCallBack;
		}else{
			$('btnAjaxLoginSubmit').show();	
			$('ajaxLoginInfo').update(json['msg']);
		}
	}
}









var firstTryInput = new Array();

function tryInput(inputId)
{
	if(firstTryInput.indexOf(inputId) == -1)
	{
		$(inputId).value = '';
		firstTryInput.push(inputId);
	}
}


function categoryPopup(idCallback, winTitle){
	var url = 'php/ajax.php?action=showCategoryPopup&callback='+idCallback;
	if($('categories')){
		url +='&categories='+$F('categories');
	}

	jsWin.instance().setOptions({width:'555', height:'400'});
	
	jsWin.instance().setContentFromUrl(url,winTitle);

}

function selectSubCat(inp){
	inp = $(inp);
	inp.up('div',0).up('div',0).select('input[type="checkbox"]').each(function(el){
		if(inp.value!=el.value){
			el.checked=inp.checked?'checked':'';	
		}
	});
	return inp.checked;
}



function fakeSelect(id,onclick,width){
	if(!width){
		width =200;
	}
	
	var sel = Builder.node('div', {className:'selector', style:'width:'+width+'px', onclick:onclick}, Builder.node('div', null, $(id).innerHTML));

   $(id).update(sel);
	
	
}

function closePopupCategory(id){
	var html = new Array();
	var values = new Array();
	$('categoryForm').select('input[type="checkbox"]').each(function(el){
		if(el.checked){
			html.push(el.name);
			values.push(el.value);
		}
	});
	
	if(!$('categories')){
		var hid = new Element('input',{id:'categories',type:'hidden',name:'categories',value:values.join(',')});
	}else{
		var hid = $('categories');
		hid.value = values.join(',');
	}
	$(id).appendChild(hid);
	$(id).select('div div')[0].innerHTML=html.join(', ');
	
	
	jsWin.instance().close();
}

function providerAddressListChanged(title,providerId, selectedValue)
{  
  showAddresses('information_index_registered_address_id', title ,providerId, selectedValue ); 
}

function showAddresses(idCallback, winTitle, providerId, selectedAddress)
{

  if(typeof jswinAddressWindow != 'undefined')
    jswinAddressWindow.close();
  
  var url = 'php/ajax.php?action=showAddressPopup&callback='+idCallback+'&providerId='+providerId+'&selectedAddress='+selectedAddress;
  

  jswinAddressWindow = new jsWin({width:800,height:650,modal:true});
  jswinAddressWindow.setContentFromUrl(url,winTitle);
  
}
function deleteProviderAddressInLine(time_stamp)
 {
 	    var addressId = $('addressId_'+time_stamp).value;
    var street = $('provider_address_street_'+time_stamp).value;
    var additional_location = $('provider_address_aditional_location_'+time_stamp).value; 
    
    var country = $('input_information_index_filter_address_window_country_'+time_stamp).value;
    var province = $('input_information_index_filter_address_window_provstate_'+time_stamp).value;
    var city = $('input_information_index_filter_address_window_city_'+time_stamp).value;
    var hood = $('input_information_index_filter_address_window_hood_'+time_stamp).value;
    var sub_hood = $('input_information_index_filter_address_window_sub_hood_'+time_stamp).value;
    
    var postal_code =  $('provider_address_postal_code_'+time_stamp).value;    
    var providerId =  $('providerId_'+time_stamp).value;
    
    
    var url = 'php/ajax.php?action=deleteProviderAddress&addressId='+addressId+'&street='+street+'&additional_location='+additional_location+'&country='+country+'&province='+province+'&city='+city+'&hood='+hood+'&sub_hood='+sub_hood+'&postal_code='+postal_code+'&providerId='+providerId;
    
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        $('error_message_'+time_stamp).show();
        $('error_message_'+time_stamp).innerHTML = rep.responseText;               
      }
      else
      {
        var newAddressId = rep.responseText;
        $('address_editor').hide();
        reloadAddressList(providerId);
      }
    }
    
 }

 function  deleteProviderAddress(time_stamp)
 {
 	    var addressId = $('addressId_'+time_stamp).value;
    var street = $('provider_address_street_'+time_stamp).value;
    var additional_location = $('provider_address_aditional_location_'+time_stamp).value; 
    
    var country = $('input_information_index_filter_address_window_country_'+time_stamp).value;
    var province = $('input_information_index_filter_address_window_provstate_'+time_stamp).value;
    var city = $('input_information_index_filter_address_window_city_'+time_stamp).value;
    var hood = $('input_information_index_filter_address_window_hood_'+time_stamp).value;
    var sub_hood = $('input_information_index_filter_address_window_sub_hood_'+time_stamp).value;
    
    var postal_code =  $('provider_address_postal_code_'+time_stamp).value;    
    var providerId =  $('providerId_'+time_stamp).value;
    
    
    var url = 'php/ajax.php?action=deleteProviderAddress&addressId='+addressId+'&street='+street+'&additional_location='+additional_location+'&country='+country+'&province='+province+'&city='+city+'&hood='+hood+'&sub_hood='+sub_hood+'&postal_code='+postal_code+'&providerId='+providerId;
    
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        $('error_message_'+time_stamp).show();
        $('error_message_'+time_stamp).innerHTML = rep.responseText;               
      }
      else
      {
        var newAddressId = rep.responseText;
        
        
         
        showAddresses('information_index_registered_address_id', 'Address Manager',providerId, newAddressId );
        reloadActualProviderList(providerId,newAddressId);  
      }
    }
    
 }

function  saveProviderAddress(time_stamp)
  {
  
    var addressId = $('addressId_'+time_stamp).value;
    var street = encodeURIComponent($('provider_address_street_'+time_stamp).value);
    var additional_location = encodeURIComponent($('provider_address_aditional_location_'+time_stamp).value); 
    
    var country = $('input_information_index_filter_address_window_country_'+time_stamp).value;    
    
    var province = $('input_information_index_filter_address_window_provstate_'+time_stamp).value;
    var city = $('input_information_index_filter_address_window_city_'+time_stamp).value;
    var hood = $('input_information_index_filter_address_window_hood_'+time_stamp).value;
    var sub_hood = $('input_information_index_filter_address_window_sub_hood_'+time_stamp).value;
    
    var postal_code =  $('provider_address_postal_code_'+time_stamp).value;    
    var providerId =  $('providerId_'+time_stamp).value;

//console.log(encodeURIComponent(street));
//console.log(time_stamp);
//console.log(street);
//console.log(country);
    var url = 'php/ajax.php?action=saveProviderAddress&addressId='+addressId+'&street='+street+'&additional_location='+additional_location+'&country='+country+'&province='+province+'&city='+city+'&hood='+hood+'&sub_hood='+sub_hood+'&postal_code='+postal_code+'&providerId='+providerId;
    
//console.log(url);
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        $('error_message_'+time_stamp).show();
        $('error_message_'+time_stamp).innerHTML = rep.responseText;               
      }
      else
      {
        var newAddressId = rep.responseText;
        
        
         
        showAddresses('information_index_registered_address_id', 'Address Manager',providerId, newAddressId );
        reloadActualProviderList(providerId,newAddressId);  
      }
    }
    
  }
  
  function  saveProviderAddressInLine(time_stamp)
  {
  
    var addressId = $('addressId_'+time_stamp).value;
    var street = $('provider_address_street_'+time_stamp).value;
    var additional_location = $('provider_address_aditional_location_'+time_stamp).value; 

    var country = $('input_information_index_filter_address_window_country_'+time_stamp).value;
        
    var province = $('input_information_index_filter_address_window_provstate_'+time_stamp).value;
    var city = $('input_information_index_filter_address_window_city_'+time_stamp).value;
    var hood = $('input_information_index_filter_address_window_hood_'+time_stamp).value;
    var sub_hood = $('input_information_index_filter_address_window_sub_hood_'+time_stamp).value;
    
    var postal_code =  $('provider_address_postal_code_'+time_stamp).value;    
    var providerId =  $('providerId_'+time_stamp).value;
    
    
    var url = 'php/ajax.php?action=saveProviderAddress&addressId='+addressId+'&street='+street+'&additional_location='+additional_location+'&country='+country+'&province='+province+'&city='+city+'&hood='+hood+'&sub_hood='+sub_hood+'&postal_code='+postal_code+'&providerId='+providerId;
	url = url.replace('#','%23');
    
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        $('error_message_'+time_stamp).show();
        $('error_message_'+time_stamp).innerHTML = rep.responseText;               
      }
      else
      {
        var newAddressId = rep.responseText;
        $('address_editor').hide();
        reloadAddressList(providerId);  
      }
    }
    
  }

function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/urlencode    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str + '').toString();
     // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

  function reloadAddressList(providerId)
  {
  	var url = 'php/ajax.php?action=getProviderAddressList&providerId='+providerId;
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        alert('Error, in reloadAddressList');      
      }
      else
      {        
        $('address_list').update(rep.responseText);  
      }
    }
  
  
  }

  function reloadActualProviderList(providerId,newAddressId)
  {
  
  var url = 'php/ajax.php?action=getProviderAddress&newAddressId='+newAddressId+'&providerId='+providerId;
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        alert('Error, in reloadActualProviderList');      
      }
      else
      {        
        $('information_index_address_wrap').innerHTML = rep.responseText;  
      }
    }
  
  
    
    
  }

function singlelocationPopup(idCallback, winTitle, inputId,locations, providerId,masterLocationId,time_stamp,type){

  if(typeof(inputId) == 'undefined' || !inputId)
  {
    inputId = 'locations';
  }

  var subLocationId = -1;
  
  switch (type)
  {
    case 'country':      
    break;
    case 'provstate':
    if($('input_information_index_filter_address_window_country_'+time_stamp).value != '')
        masterLocationId = $('input_information_index_filter_address_window_country_'+time_stamp).value;
    break;
    case 'city':
    if($('input_information_index_filter_address_window_provstate_'+time_stamp).value != '')
        masterLocationId = $('input_information_index_filter_address_window_provstate_'+time_stamp).value;
    break;
    case 'hood':
      if($('input_information_index_filter_address_window_city_'+time_stamp).value != '')
        masterLocationId = $('input_information_index_filter_address_window_city_'+time_stamp).value;
    break;
    case 'sub_hood':
      if($('input_information_index_filter_address_window_hood_'+time_stamp).value != '')
        masterLocationId = $('input_information_index_filter_address_window_hood_'+time_stamp).value;
    break;
    
  }
  
  var url = 'php/ajax.php?action=showSingleLocationPopup&callback='+idCallback+'&inputId='+inputId+'&locations='+locations+'&providerId='+providerId+'&masterLocationId='+masterLocationId+'&time_stamp='+time_stamp+'&type='+type;
  
  if($(inputId)){
    url +='&locations='+$F(inputId);
  }

  jswinSingleLocationAddressWindow = new jsWin({width:800,height:650,modal:true});
  jswinSingleLocationAddressWindow.setContentFromUrl(url,winTitle);
  
/*
  jsWin.instance().setOptions({width:'555', height:'400'});

  jsWin.instance().setContentFromUrl(url,winTitle);
*/
}


function multiplelocationPopup(idCallback, winTitle, inputId, locations,providerId, time_stamp){

  if(typeof(inputId) == 'undefined' || !inputId)
  {  
    inputId = 'locations';
  }

if(time_stamp > 0)
  masterLocationId = $('input_information_index_filter_address_window_provstate_'+time_stamp).value;
else
  masterLocationId = -1; //defalut 


  var url = 'php/ajax.php?action=showMultipleLocationPopup&callback='+idCallback+'&inputId='+inputId+'&locations='+locations+'&providerId='+providerId+'&masterLocationId='+masterLocationId;
  if($(inputId)){
    url +='&locations='+$F(inputId);
  }

  jsWin.instance().setOptions({width:'800', height:'600',modal:true});

  jsWin.instance().setContentFromUrl(url,winTitle);

}


function goToQuebec()
{
	$('locations_container').style.top = 0 + 'px';	 
}



function goToOntario()
{
	var ontario_offset = $('ontario').positionedOffset();
	var ontario_offset_top = ontario_offset[1];   
   
   $('locations_container').style.top = '-' + ontario_offset_top + 'px';	 
}


function providerProfilePopup(idCallback, winTitle, providerId, video){

  var url = 'php/ajax.php?action=showProviderProfile&callback='+idCallback+'&providerId='+providerId;
  
  if(video)
    jsWin.instance().setOptions({width:'700', height:'600'});
  else
    jsWin.instance().setOptions({width:'700', height:'370'});
  

  jsWin.instance().setContentFromUrl(url,winTitle);
  
}

function seeVideo(idCallback, videoUrl,winTitle)
{
  var url = 'php/ajax.php?action=showProviderVideo&callback='+idCallback+'&videoUrl='+videoUrl;
  jsWin.instance().setOptions({width:'700', height:'370'});
  jsWin.instance().setContentFromUrl(url,winTitle);
}

function showFeedBackWindow()
{
    winTitle = 'FeedBack';
    var url = 'php/ajax.php?action=showFeedBackForm';
  
    jsWin.instance().setOptions({width:'400', height:'400'});

   jsWin.instance().setContentFromUrl(url,winTitle);



}



function eventsPopup(idCallback, winTitle, providerId, categoryId, hoodId, age){

	var url = 'php/ajax.php?action=showProviderEvents&callback='+idCallback+'&providerId='+providerId+'&categoryId='+categoryId+'&hoodId='+hoodId+'&age='+age;
	
	jsWin.instance().setOptions({width:'1200', height:'600'});

	jsWin.instance().setContentFromUrl(url,winTitle);

}

function eventRegistyrationPopup(idCallback, winTitle, eventORCId){

	var url = 'php/ajax.php?action=showProviderEventRegistration&callback='+idCallback+'&eventId='+eventORCId+'&serviceProviderName='+winTitle;
	
	jsWin.instance().setOptions({width:'1200', height:'600'});
	

	jsWin.instance().setContentFromUrl(url,winTitle);
	
	

}

//This is the same function as in the jsWin.js file, but with different margins, so that k3soft code remains intact
function maximizeModalWindow(obj, marginWidth, marginHeight){

		var viewportSize	= document.viewport.getDimensions();
		setWidthModalWindow(obj, viewportSize['width']-marginWidth);
		setHeightModalWindow(obj, viewportSize['height']-marginHeight);
		obj.center();
	}


function setWidthModalWindow(obj,w){
		w = Math.min(document.viewport.getWidth(), w);
		Element.setStyle(obj.element,{width:parseInt(w)+10+"px"});
	}
	
function setHeightModalWindow(obj, h){
		h = Math.min(document.viewport.getHeight(), h);
		if(parseInt(h)!= 0){
			Element.setStyle(obj.content,{height:parseInt(h)+"px"});
		}else{
			Element.setStyle(obj.content,{height:'auto'});
		}
	}


function eventRegistyrationLoginPopup(idCallback, winTitle, userId, userPwd, eventId)
{

  //var url = 'php/ajax.php?action=showProviderEventRegistrationLogin&callback='+idCallback+'&userId='+userId+'&userPwd='+userPwd+'&eventId='+eventId;
  var url = 'https://www.onlineregistrationcenter.com/provider_login.asp?pid='+userId+'&password='+userPwd+'&m=253';
  
  if(eventId > 0)
  {
    url = url+'&event_id='+eventId;
  }
  
    
    var params = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,height='+window.screen.availHeight+',width='+window.screen.availWidth;
    
   
  
    newwindow=window.open(url,winTitle,params);
      if (window.focus) {newwindow.focus()}
  
   
  
  //    	var url = 'php/ajax.php?action=showProviderEventRegistrationLogin&callback='+idCallback+'&userId='+userId+'&userPwd='+userPwd+'&eventId='+eventId;
  //    	jsWin.instance().setOptions({width:'1200', height:'600'});
  //    	jsWin.instance().setContentFromUrl(url,winTitle);
  //    	maximizeModalWindow(jsWin.instance(), 15, 80);
  

}

function toggleActivities(id2)
{
	document.getElementById(id2).toggle('slide');
}


function submitFormById(formID)
{
	document.getElementById(formID).submit();
}

function categoriesWithSelectedPopup(idCallback, winTitle, inputId, providerId)
{
      if(typeof(inputId) == 'undefined' || !inputId)
      {
        inputId = 'categories';
      }
    
      var url = 'php/ajax.php?action=showCategoriesWithSelectedPopup&callback='+idCallback+'&inputId='+inputId+'&providerId='+providerId;
      if($(inputId)){
        url +='&categories='+$F(inputId);
      }
    
      jsWin.instance().setOptions({width:'600', height:'400'});
    
      jsWin.instance().setContentFromUrl(url,winTitle);
	
}

/* Deprecated by the function "singleLocationSelected"
function closePopupSingleLocation(id, inputId){

  if(typeof(inputId) == 'undefined' || !inputId)
  {
    inputId = 'information_city_filter';
  }

  var html = new Array();
  var values = new Array();
  $('locationFormSingleLocation').select('input[type="radio"]').each(function(el){
    if(el.checked)
    {
      var city_name = el.value.split('|')[0];
      var city_id = el.value.split('|')[1];
    
      html.push(city_name);
      values.push(city_id);
      alert(city_name);
    }
  });
  if(!$(inputId)){
    var hid = new Element('input',{id:inputId,type:'hidden',name:'Singlelocation',value:values.join(',')});
  }else{
    var hid = $(inputId);
    hid.value = values.join(',');
  }
  $(id).appendChild(hid);
  if(id!='upcoming_locations'){
    $(id).select('div div')[0].innerHTML=html.join(', ');
  }else{
   $('upcoming_locations').submit();
  }
  
  alert(values.join(','));
  alert($(id).select('div div')[0].innerHTML);
  
  //jswinAddressWindow.close();
  jswinSingleLocationAddressWindow.close();
}
*/

function singleLocationSelected(id, locationId, locationName, time_stamp,type)
{
    
  $('input_information_index_filter_address_window_'+type+'_'+time_stamp).value = locationId;
  $('information_index_filter_address_window_'+type+'_'+time_stamp).select('div div')[0].innerHTML=locationName;


  switch(type)
  {
    case 'country':
      $('input_information_index_filter_address_window_provstate_'+time_stamp).value = '';
      $('information_index_filter_address_window_provstate_'+time_stamp).select('div div')[0].innerHTML='';
    break;
    case 'provstate':
      $('information_index_filter_address_window_city_'+time_stamp).value = '';
      $('information_index_filter_address_window_city_'+time_stamp).select('div div')[0].innerHTML='';
    break;
    case 'city':
      $('input_information_index_filter_address_window_hood_'+time_stamp).value = '';
      $('information_index_filter_address_window_hood_'+time_stamp).select('div div')[0].innerHTML='';
    break;
    case 'hood':
      $('input_information_index_filter_address_window_sub_hood_'+time_stamp).value = '';
      $('information_index_filter_address_window_sub_hood_'+time_stamp).select('div div')[0].innerHTML='';
    break;
   
  }

  jswinSingleLocationAddressWindow.close();
}

function closePopupLocation(id, inputId){


	if(typeof(inputId) == 'undefined' || !inputId)
	{
		inputId = 'locations';		
	}

	var html = new Array();
	var values = new Array();
	$('locationForm').select('input[type="checkbox"]').each(function(el){
		if(el.checked){
			html.push(el.name);
			values.push(el.value);
		}
	});
	
		
	if(!$(inputId))
	{
		var hid = new Element('input',{id:inputId,type:'hidden',name:'locations',value:values.join(',')});
	}
	else
	{
		var hid = $(inputId);
		hid.value = values.join(',');
	}
	
	
	$(id).appendChild(hid);
	if(id!='upcoming_locations'){
		$(id).select('div div')[0].innerHTML=html.join(', ');
	}else{
		$('upcoming_locations').submit();
	}
	
	jsWin.instance().close();
	
}

function popCalendar(id, withTime, yearRange, defaultDate){

	if(typeof(withTime) == 'undefined')
	{
		withTime = true;
	}

	if(typeof(yearRange) == 'undefined')
	{
		yearRange = [1980,2011];
	}

	new CalendarDateSelect(id, {
			popup:"force",
			time:withTime,
			year_range:yearRange,
			default_date:defaultDate
			//time:$F(id)
	});

	Date.prototype.toFormattedString = function(include_time){

		str = this.getFullYear() + '-' + doublezero(this.getMonth()+1) + "-" + doublezero(this.getDate());

		if (include_time)
		{
			hour = this.getHours();
			str += " " + this.getAMPMHour() + ":" + this.getPaddedMinutes() //" " + this.getAMPM()
		}

		return str
	}
}

function doublezero(num){
	if(num < 10 ){
		return '0'+num.toString();
	}
	return num;
}


function toggleReminder(id,a){
	jsWin.instance().setTitle('Reminder');
	jsWin.instance().setContent('Loading...');
	jsWin.instance().show();
	
	
	var aj = new Ajax.Request('php/ajax.php?action=setReminder',{postBody:'id='+id});
	aj.options.onSuccess = function(rep){
		jsWin.instance().setContent(rep.responseText);
		if($(a).hasClassName('alarmOff')){
			$(a).removeClassName('alarmOff');
			$(a).addClassName('alarmOn');
		}else{
			$(a).removeClassName('alarmOn');
			$(a).addClassName('alarmOff');
		}
	}
}

/*function removeEvent(id){
	
	jsWin.instance().setTitle('Remove event from my calendar');
	jsWin.instance().setContent('<div style="text-align:center;">Do you want to remove the occurence of the event or the entire event from your calendar?<br/><a href="php/ajax.php?action=removeEventCalendar&type=occ&id='+id+'">Remove this occurence</a>&nbsp;&nbsp;&nbsp;<a href="php/ajax.php?action=removeEventCalendar&type=full&id='+id+'">Remove all the occurences from my calendar</a></div>');
	jsWin.instance().show();
}
*/

function initTooltipNotice()
{
	$$('.tooltip_notice').each(function(el)
	{	//console.debug(el.identify());

		if(!$('tooltip_'+el.identify()))
		{
			var span = Builder.node('span',{id:'tooltip_'+el.identify(),className:'tooltipBtn'},'?');
			new Insertion.After(el, span);
	
			new Effect.Tooltip(span, '<div style="font-weight:bold;">'+el.readAttribute('title') + '</div><div style="margin-top:3px;">' + el.innerHTML + '</div>', {className: 'tooltip', offset:{x:4, y:4}});
		}
	});
}

function checkPostalCode(elementId)
{
	var regEx = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
	var postal_code = document.getElementById(elementId).value;

	if(!regEx.test(postal_code))
	{
		alert("The Postal Code Format should be A1B-2C3");
		document.getElementById(elementId).value = '';
	}
	
}

function checkEmail(elementId)
{
	var regEx = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	var email = document.getElementById(elementId).value;

	if(!regEx.test(email))
	{
		alert("The Email Format should be name@host.com");
		document.getElementById(elementId).value = '';
	}
	
}

function clearMainSearch()
{
	document.getElementById("keyword").value = '...';
	document.main_search.category.selectedIndex = 0;
	document.main_search.neighbourhood.selectedIndex = 0;
	document.main_search.minage.selectedIndex = 0;
}



function clearFeedbackSubject()
{
  element = document.getElementById('subject');
  
  if(element.value == 'Please enter a Title' || element.value == 'Veuillez inscrire une Titre')
  {
    element.value = '';
    element.setAttribute('class', '');
  }
    
}

function clearFeedbackEmail()
{
  element = document.getElementById('email');
  
  if(element.value == 'Please enter your Email' || element.value == 'Veuillez inscrire votre Courriel')
  {
    element.value = '';
    element.setAttribute('class', '');
  }
    
}

function clearFeedbackDescription()
{
  element = document.getElementById('main_description');
  
  if(element.value == 'How would you describe it?' || element.value == 'Comment le décririez-vous?')
  {
    element.value = '';
    element.setAttribute('class', '');
  }
}

function toggleSearchResults(id_to_show,id_to_hide)
{
	$(id_to_show).show();
	$(id_to_hide).hide();
	
	$(id_to_show + '_tab').removeClassName('not_selected');
	$(id_to_show + '_tab').addClassName('selected');
	
	$(id_to_hide + '_tab').removeClassName('selected');
	$(id_to_hide + '_tab').addClassName('not_selected');
	
	$(id_to_show + '_grey').show();
	$(id_to_hide + '_grey').hide();

	
	
}

Event.observe(window,'load', function(e)
{
	initTooltipNotice();
});

function recalculateTax(id_price_no_tax, id_price_tps, id_price_tvq, id_price_total, id_apply_tax)
{
  if($(id_apply_tax).checked)
  {
	var tps = 0.05;
	var tvq = 0.095;
	var no_tax = $(id_price_no_tax).value;
		
	$(id_price_tps).value = number_format(roundNumber(no_tax * tps, 2), 2, '.', '');
	$(id_price_tvq).value = number_format(roundNumber((no_tax*1 + (no_tax * tps)) * tvq, 2), 2, '.', '');
	$(id_price_total).value = number_format(roundNumber(no_tax*1 + (no_tax * tps) + ((no_tax*1 + (no_tax * tps)) * tvq), 2), 2, '.', '');
	
	}
	else
	{
	  $(id_price_total).value = $(id_price_no_tax).value;
	}
	
}

function recalculateTaxON(id_price_no_tax, id_price_hst, id_price_total, id_apply_tax)
{
  if($(id_apply_tax).checked)
  {		
	var hst = 0.13;
	var no_tax = $(id_price_no_tax).value;			
	
	$(id_price_hst).value = number_format(roundNumber(no_tax * hst, 2), 2, '.', '');		
	$(id_price_total).value = number_format(roundNumber(no_tax*1 + (no_tax * hst), 2), 2, '.', '');
	
	}
	else
	{
	  $(id_price_total).value = $(id_price_no_tax).value;
	}
	
}


function number_format (number, decimals, dec_point, thousands_sep) {
	 number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


      function myLoad(rank)
        {
          new Effect.Appear('element_id');
        
        var s2 = new Control.Slider('handle2','track2', {axis:'horizontal', sliderValue:rank, increment: 50, range: $R(1,1000), values: [1,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000]});
        s2.options.onChange = function(value){
                $('information_index_ranking').value = value;
            };
        $('information_index_ranking').value = s2.value;

          }
          
function togglePartners(scoopCardCheckbox)
{
  if(scoopCardCheckbox.checked)
  {
    $('information_index_partners').show();
  }
  else
  {
    $('information_index_partners').hide();
  }
}

/* Started to make a service provider creation via Ajax, but Noticed it is already developed
function createProviderAjax(idCallback)
{
  var id = 'information_index_profile_name';
  var tmp_name = $(id).value; 
  
  $('message').innerHtml = 'Please wait...';
  $(id).readOnly = true;
  
  var url = 'php/ajax.php?action=createProvider&callback='+id+'&sp_name='+$(id).value;
  var aj = new Ajax.Request(url,{postBody:'id='+id});
  aj.options.onSuccess = function(rep){
  
    //Capture the Error
    if(rep.responseText.indexOf("Error") != -1)
    {
        var error = rep.responseText.split('|')[1];
        
        $('message').innerHtml = error; 
        
        $(id).value = tmp_name;
        $(id).readOnly = false;      
    }
    else
    {
    $('message').innerHtml = '';
      $('provider_id').value = rep.responseText; 
      $(id).value = tmp_name;
      $(id).readOnly = false;  
    }
  }
}
*/

function eventManagerFormUpdatedWithProvider(formId, providerId)
{
  if(providerId != 0 && providerId != "" && providerId != null)
  {
    AjaxRequest.formsUpdated.set($(formId).identify(), true);
  
    AjaxRequest.currentFormUpdated = $(formId);
  
    if(!$($(formId).identify()+'__form_updated'))
    {
      Insertion.Bottom($(formId), '<input type="hidden" name="_form_updated" value="1" id="'+$(formId).identify()+'__form_updated" />');
    }
  }
}

function updateCity(province_element, timestamp)
{
  var provinceId =province_element.value;
  
  //input_information_index_filter_address_window_city_
  alert(provinceId);
  
}

function updateProvince(country_element, timestamp)
{
  var countryId =country_element.value;
  var url = 'php/ajax.php?action=updateProvince&countryId='+countryId+'&timestamp='+timestamp;
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {
        alert('Error, in updateProvince()');      
      }
      else
      {        
        $('prov_info').innerHTML = rep.responseText;
      }
    }
}

  

function microtime (get_as_float) {
    // Returns either a string or a float containing the current time in seconds and microseconds  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/microtime    // +   original by: Paulo Freitas
    // *     example 1: timeStamp = microtime(true);
    // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10); 
    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

function changeCatalogName(cataloge_id)
{
  var catalogue_name = $('catalog_name_'+cataloge_id).value;
   
  var url = 'php/ajax.php?action=changeCatalogName&cataloge_id='+cataloge_id+'&catalogue_name='+escape(catalogue_name);
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
      if(rep.responseText == 'OK')
      {      
        $('catalog_name_changed_'+cataloge_id).innerHTML = 'Name Changed';
        $('catalog_name_changed_'+cataloge_id).addClassName('catalog_name_change');
        $('catalog_name_changed_'+cataloge_id).removeClassName('catalog_name_not_changed');
      }
      else
      {        
        console.log(rep.responseText +' != '+ catalogue_name);       
        $('catalog_name_changed_'+cataloge_id).addClassName('catalog_name_not_changed');
        $('catalog_name_changed_'+cataloge_id).removeClassName('catalog_name_change');
        $('catalog_name_changed_'+cataloge_id).innerHTML = 'Name Not Changed';
      }     
    }    
}

function setNewSpActiveStatus(sp_id)
{
	var current_active_status = $('active_status_value_'+sp_id).innerHTML;
 	var new_active_status = -1;
 	var new_status_str = '';
 	var	new_class = '';
 	var	new_class = '';
 	
 	if(current_active_status == 0)
 	{
 		new_active_status = 1;
 		new_status_str = 'Active';
 		new_class = 'green';
 		old_class = 'red'; 
 	}
 	else
 	{
 		new_active_status = 0;
 		new_status_str = 'Not Active';
 		new_class = 'red';
 		old_class = 'green';
 	}
	
   
  var url = 'php/ajax.php?action=setNewSpActiveStatus&user_id='+sp_id+'&active_status_new='+new_active_status;
    
    var aj = new Ajax.Request(url,{});
    aj.options.onSuccess = function(rep)
    {
      if(rep.responseText == new_active_status)
      {       	
        $('active_status_'+sp_id).innerHTML = new_status_str;
        $('active_status_'+sp_id).addClassName(new_class);
        $('active_status_'+sp_id).removeClassName(old_class);
        $('active_status_value_'+sp_id).innerHTML = new_active_status;
      }
      else
      {   
      	alert('There was a problem: '+  rep.responseText);           
      }     
    }    
}

function editCurrentAddress(selectId, providerId)
{	
	var selectedAddress = $(selectId).value;
    var url = 'php/ajax.php?action=showAddressInPage&providerId='+providerId+'&selectedAddress='+selectedAddress;
    var aj = new Ajax.Request(url,{});
    
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {        
        $('address_editor').update('ERROR: '+ rep.responseText);    
    	$('address_editor').show();                       
      }
      else
      {
        var response = rep.responseText;        
    	$('address_editor').update(response);    
    	$('address_editor').show();
      }
    }
}

function addNewAddress(providerId)
{
	var selectedAddress = 'new_address';
    var url = 'php/ajax.php?action=showAddressInPage&providerId='+providerId+'&selectedAddress='+selectedAddress;
    var aj = new Ajax.Request(url,{});
    
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {        
        $('address_editor').update('ERROR: '+ rep.responseText);    
    	$('address_editor').show();                       
      }
      else
      {
        var response = rep.responseText;        
    	$('address_editor').update(response);    
    	$('address_editor').show();
      }
    }
}

function setSelectedAddress(providerId, selectId)
{
	var selectedAddress = $(selectId).value;
    var url = 'php/ajax.php?action=setSelectedProviderAddress&providerId='+providerId+'&selectedAddress='+selectedAddress;
    var aj = new Ajax.Request(url,{});
    
    aj.options.onSuccess = function(rep)
    {
  
      //Capture the Error
      if(rep.responseText.indexOf("Error") != -1)
      {        
        $('address_editor').update('ERROR: '+ rep.responseText);    
    	$('address_editor').show();                       
      }
      else
      {
        var response = rep.responseText;                 	
      }
    }	
}
