var $j = jQuery.noConflict();

var UPLOADED_FILES_INDEX = 0;
var UPLOADED_FILES = new Array();
var CONTROLLER_URL = '/property/realestate';
var LOGIN_USER_ID = 0

function setBaseURL(baseUrl)
{
	CONTROLLER_URL = baseUrl
}
function uplodifyAll()
{	 
	 uplodify();   
   uplodifySWF();   
   uplodifyVideo();   
   uplodifyPhoto();      
   load();
}  

function initialize() { 
  var map = new GMap2(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(42.89276, 11.53475), 13);
  map.addControl(new GSmallMapControl());

 
  // Add 10 markers to the map at random locations
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var lngSpan = northEast.lng() - southWest.lng();
  var latSpan = northEast.lat() - southWest.lat();
  var point = new GLatLng(42.89276,11.53475);
    map.addOverlay(new GMarker(point));
	map.setCenter(point, 13);
	var marker = new GMarker(point);
	map.addOverlay(marker);
	marker.openInfoWindowHtml(info);
}

function load()
{
	 if(GBrowserIsCompatible() && document.getElementById('map_canvas'))
   {

      //var oldLat = opener.document.getElementById('field_'+ opener.document.getElementById('gps_lat').value).value;
      //var oldLng = opener.document.getElementById('field_'+ opener.document.getElementById('gps_lng').value).value;
      //var oldLat = null;
      //var oldLng = null;
      //(oldLat && oldLng) ? initialCenter = new GLatLng(oldLat, oldLng) : initialCenter = new GLatLng(37.985238, -122.590814); 
      var oldLat = document.getElementById("latitude").value;
      var oldLng = document.getElementById("longitude").value;
      (oldLat && oldLng) ? initialCenter = new GLatLng(oldLat, oldLng) : initialCenter = new GLatLng(42.76667, 11.13333); 
      

      document.getElementById('latitude').value = initialCenter.lat();
      document.getElementById('longitude').value = initialCenter.lng();
        
      var map = new GMap2(document.getElementById('map_canvas'));
      map.setCenter(initialCenter, 13);
      map.addOverlay(new GMarker(initialCenter));
      GEvent.addListener(map,"click", function(overlay,latlng)
      {
         document.getElementById("latitude").value = latlng.lat();
         document.getElementById("longitude").value = latlng.lng();
         opener.document.getElementById("field_"+opener.document.getElementById('gps_lat').value).value = latlng.lat();
         opener.document.getElementById("field_"+opener.document.getElementById('gps_lng').value).value = latlng.lng();
      });
      map.enableGoogleBar();
   }
}

function getProvinceList(regionObj,holderType)
{
	if(holderType == 'full'){
	 var _url = CONTROLLER_URL + "/index.php?r=admin/buildinginfo/provincelist"; 
	 }else
	 	{
	 		var _url = CONTROLLER_URL + "/index.php?r=site/provincelist";
	 	}
   
   if(holderType == 'adv')
   {
      var _data = "region_code=" + regionObj.value+"&holder_type="+holderType;
    }else
    	{
    		var _data = "region_code=" + regionObj.value;
    	}
   
   $j.ajax({
      type: 'post',
      url: _url,
      data: _data,
      dataType: '',
      async: false,
      success: function(json)
      {
      	if(holderType == 'adv')
      	{
      		$j("#adv_province_holder").html(json);         
      	}
      	else if(holderType == 'full')
      	{
         $j("#full_province_holder").html(json);         
        }
        else{
        	$j("#province_holder").html(json);         
        }
      }
   });
}
function getCityList(provinceObj,holderType)
{
	 if(holderType == 'full'){
	 var _url = CONTROLLER_URL + "/index.php?r=admin/buildinginfo/citylist"; 
	 }else
	 	{
	 		var _url = CONTROLLER_URL + "/index.php?r=site/citylist"; 
	 	}
	 
	 
   var _data = "province_code=" + provinceObj.value;
   
   $j.ajax({
      type: 'post',
      url: _url,
      data: _data,
      dataType: '',
      async: false,
      success: function(json)
      {
      	if(holderType == 'adv')
      	{
      		$j("#adv_city_holder").html(json);         
      	}
      	else if(holderType == 'full')
      	{
          $j("#full_city_holder").html(json);         
        }
        else
        {
        	$j("#city_holder").html(json);
        }
      }
   });
}

function getTipologiaList(categoryname)
{
	$j("#tipologiaholder").html('Loading....');
   var _url = CONTROLLER_URL + "/index.php?r=site/tipologialist&categoryname="+ escape(categoryname); 
   var _data = "categoyname=" + escape(categoryname);   
   $j.ajax({
      type: 'post',
      url: _url,
      data: _data,
      dataType: '',
      async: false,
      success: function(json)
      {
       $j("#tipologiaholder").html(json);
      }
   });
}
function checkNSubmit()
{
	 var is_error = false;         
   var message = '';
   clearMessages();   
      
   if(!$j('#BuildingInfo_contract').val())
   {
      message += printMessage(BuildingInfo_contract);
      is_error = true;
   }
   if(!$j('#BuildingInfo_country').val())
   {
      message += printMessage(BuildingInfo_country);
      is_error = true;
   }
   if(!$j('#binfo_region_code').val())
   {
      message += printMessage(BuildingInfo_region_code);
      is_error = true;
   }
   if(!$j('#binfo_province_code').val())
   {
      message += printMessage(BuildingInfo_province_code);
      is_error = true;
   }
   if(!$j('#binfo_city_code').val())
   {
      message += printMessage(BuildingInfo_city_code);
      is_error = true;
   }
   if(!$j('#BuildingInfo_category').val())
   {
      message += printMessage(BuildingInfo_category);
      is_error = true;
   }
   
  /* if($j('#binfo_building_type'))
   	{
	   if(!$j('#binfo_building_type').val())
	   {
		  message += 'dedede'+printMessage(BuildingInfo_building_type);
		  is_error = true;
	   }	
	}
	
	if($j('#BuildingInfo_building_type'))
	  {
	   if(!$j('#BuildingInfo_building_type').val())
	   {
		  message += 'adada'+ printMessage(BuildingInfo_building_type);
		  is_error = true;
	   }			
	  }*/

   if(!$j('#BuildingInfo_price').val())
   {
      message += printMessage(BuildingInfo_price);
      is_error = true;
   }
   
   if(!$j('#BuildingInfo_surface').val())
   {
      message += printMessage(BuildingInfo_surface);
      is_error = true;
   }
   if(!$j('#BuildingInfo_rooms_locations').val())
   {
      message += printMessage(BuildingInfo_rooms_locations);
      is_error = true;
   }
      
   if(is_error)
   {     
   	  var errorSummary = "<p>Per favore, correggere i seguenti errori di input:</p><ul>"+message+"</ul>";
   	  $j("#building-info-form_es_").html(errorSummary);
      $j("#building-info-form_es_").show();
      
      return false;
   }
   else
   {      
     $j('#uploaded_files').val(UPLOADED_FILES.join("::"));
    
     //$j('#tickets-form').submit(); 
     return true;
   }   
}

function clearMessages()
{
	$j(".errorSummary").html("");
}
var BuildingInfo_name = "Nome non pu&ograve; essere nullo.";
var BuildingInfo_email = "Email non pu&ograve; essere nullo.";
var BuildingInfo_cell_phone = "Cellulare non pu&ograve; essere nullo.";
var BuildingInfo_contract = "Contratto non pu&ograve; essere nullo.";
var BuildingInfo_country = "Nome non puņ essere nullo.";
var BuildingInfo_region_code = "Regione non pu&ograve; essere nullo.";
var BuildingInfo_province_code = "Provincia non pu&ograve; essere nullo.";
var BuildingInfo_city_code = "Comune non pu&ograve; essere nullo.";
var BuildingInfo_category = "Categoria non pu&ograve; essere nullo.";
var BuildingInfo_building_type = "Tipologia non pu&ograve; essere nullo.";
var BuildingInfo_price = "Prezzo non pu&ograve; essere nullo.";
var BuildingInfo_price_numeric = "Prezzo deve essere un intero.";
var BuildingInfo_rooms_locations_numeric = "Vani / Locali deve essere un intero.";

var BuildingInfo_surface = "Superficie non pu&ograve; essere nullo.";
var BuildingInfo_surface_numeric = "Superficie deve essere un intero.";

var BuildingInfo_rooms_locations = "Vani / Locali non pu&ograve; essere nullo.";

function printMessage(msg)
{	
	return "<li>"+msg+"</li>";
}
function checkSrcSubmit()
{
	$j("#lbl_price").removeClass("error");
	$j("#lbl_rooms_locations").removeClass("error");      
	var is_error = false;         
	 if(($j('#price_min').val() && !$j('#price_min').val().match(/^\d+$/)) || ($j('#price_max').val() && !$j('#price_max').val().match(/^\d+$/)))
   {
      $j("#lbl_price").addClass("error");
      is_error = true;
   }
   
   if(($j('#rooms_locations_min').val() && !$j('#rooms_locations_min').val().match(/^\d+$/)) || ($j('#rooms_locations_max').val() && !$j('#rooms_locations_max').val().match(/^\d+$/)))
   {
   	  $j("#lbl_rooms_locations").addClass("error");      
      is_error = true;
   }
      
   if(is_error)
   {     
   	  alert("Inserire un valore numerico nei campi evidenziati")   	  
      
      return false;
   }
   else
   {
     return true;
   }
}
function checkSrcAdvSubmit()
{
	$j("#adv_lbl_price").removeClass("error");     
	$j("#adv_lbl_rooms_locations").removeClass("error"); 
	$j("#adv_lbl_surface").removeClass("error");          
	$j("#adv_lbl_bathrooms").removeClass("error");
	   
	var is_error = false;         
	if(($j('#adv_price_min').val() && !$j('#adv_price_min').val().match(/^\d+$/)) || ($j('#adv_price_max').val() && !$j('#adv_price_max').val().match(/^\d+$/)))
   {
   	  $j("#adv_lbl_price").addClass("error");             
      is_error = true;
   }
   
   if(($j('#adv_rooms_locations_min').val() && !$j('#adv_rooms_locations_min').val().match(/^\d+$/)) || ($j('#adv_rooms_locations_max').val() && !$j('#adv_rooms_locations_max').val().match(/^\d+$/)))
   {
      $j("#adv_lbl_rooms_locations").addClass("error");      
      is_error = true;
   }
   
   if(($j('#adv_surface_min').val() && !$j('#adv_surface_min').val().match(/^\d+$/)) || ($j('#adv_surface_max').val() && !$j('#adv_surface_max').val().match(/^\d+$/)))
   {
      $j("#adv_lbl_surface").addClass("error");
      is_error = true;
   }
   if(($j('#adv_bathrooms').val() && !$j('#adv_bathrooms').val().match(/^\d+$/)))
   {
      $j("#adv_lbl_bathrooms").addClass("error");
      is_error = true;
   }
   if(is_error)
   {        	  
   	  
   	  alert("Inserire un valore numerico nei campi evidenziati")   	  
      
      return false;
   }
   else
   {
     return true;
   }
}
function checkUserSubmit()
{
   var is_error = false;         
   var message = '';
   clearMessages();   
   
   $j('#BuildingInfo_name').val(trim($j('#BuildingInfo_name').val()));
   $j('#BuildingInfo_last_name').val(trim($j('#BuildingInfo_last_name').val()));
   $j('#BuildingInfo_email').val(trim($j('#BuildingInfo_email').val()));
   $j('#BuildingInfo_cell_phone').val(trim($j('#BuildingInfo_cell_phone').val()));
   
   if(!$j('#BuildingInfo_name').val())
   {         	
   	  var data = printMessage(BuildingInfo_name);
      message += data;      
      is_error = true;
   }
   // 
   if(!$j('#BuildingInfo_email').val())
   {
      message += printMessage(BuildingInfo_email);
      is_error = true;
   }
   if(!$j('#BuildingInfo_cell_phone').val())
   {
      message += printMessage(BuildingInfo_cell_phone);
      is_error = true;
   }
   if(!$j('#BuildingInfo_contract').val())
   {
      message += printMessage(BuildingInfo_contract);
      is_error = true;
   }
   if(!$j('#BuildingInfo_country').val())
   {
      message += printMessage(BuildingInfo_country);
      is_error = true;
   }
   if(!$j('#binfo_region_code').val())
   {
      message += printMessage(BuildingInfo_region_code);
      is_error = true;
   }
   if(!$j('#binfo_province_code').val())
   {
      message += printMessage(BuildingInfo_province_code);
      is_error = true;
   }
   if(!$j('#binfo_city_code').val())
   {
      message += printMessage(BuildingInfo_city_code);
      is_error = true;
   }
   if(!$j('#BuildingInfo_category').val())
   {
      message += printMessage(BuildingInfo_category);
      is_error = true;
   }
   if(!$j('#BuildingInfo_building_type').val())
   {
      message += printMessage(BuildingInfo_building_type);
      is_error = true;
   }
   if(!$j('#BuildingInfo_price').val())
   {
      message += printMessage(BuildingInfo_price);
      is_error = true;
   }
   if($j('#BuildingInfo_price').val() && !$j('#BuildingInfo_price').val().match(/^\d+$/))
   {
      message += printMessage(BuildingInfo_price_numeric);
      is_error = true;
   }
   
   if(!$j('#BuildingInfo_surface').val())
   {
      message += printMessage(BuildingInfo_surface);
      is_error = true;
   }
   if($j('#BuildingInfo_surface').val() && !$j('#BuildingInfo_surface').val().match(/^\d+$/))
   {
      message += printMessage(BuildingInfo_surface_numeric);
      is_error = true;
   }
   if(!$j('#BuildingInfo_rooms_locations').val())
   {
      message += printMessage(BuildingInfo_rooms_locations);
      is_error = true;
   }
      
   if(is_error)
   {     
   	  var errorSummary = "<p>Per favore, correggere i seguenti errori di input:</p><ul>"+message+"</ul>";
   	  $j("#building-info-form_es_").html(errorSummary);
      $j("#building-info-form_es_").show();
      
      return false;
   }
   else
   {      
     $j('#uploaded_files').val(UPLOADED_FILES.join("::"));
    
     //$j('#tickets-form').submit(); 
     return true;
   }
}
/*
function printMessage(_message_id, _message_text)
{
   $j('#'+_message_id).html(_message_text);
}
*/
function clearMessage(_message_id)
{
   $j('#'+_message_id).html('');
}

function trim(_text)
{
   return _text.replace(/^\s*|\s*$/g,'');
}

function clearNewTicketEditorMessages()
{
   clearMessage("title_msg");
   clearMessage("source_msg");
   clearMessage("notes_msg");
   clearMessage("priority_msg");
}
function uplodify(){

	/*$j("#uploadify_file").uploadify({
		'uploader'       : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/uploadify.swf',
		'script'         : CONTROLLER_URL+'/index.php?r=admin/buildinginfo/uploadyfy/file_type/file',
		'cancelImg'      : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/cancel.png',
		'folder'         : '',
		'queueID'        : 'fileQueue',
		'buttonText'     : 'Allega File',
		'wmode'          : 'transparent',
		'auto'           : true,
		'multi'          : true,
		'onProgress'     : true,
		'onError'        : function(event, queueID, fileObj, errorObj){
								 alert('error');
			                     alert(errorObj);  
                           //displayAttachments(fileObj, response);
                         },
		'onComplete'     : function(event, queueID, fileObj, response, data){		                     
                           displayAttachments(fileObj, response,'file');
                         }
	});  */
	$j("#uploadify_file").uploadify({
		'uploader'       : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/uploadify.swf',
		'script'         : CONTROLLER_URL+'/index.php?r=admin/buildinginfo/uploadyfy/file_type/file',
		'cancelImg'      : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/cancel.png',
		'folder'         : '',
		'queueID'        : 'fileQueue',
		'buttonText'     : 'Allega Foto',
		'wmode'          : 'transparent',
		'auto'           : true,
		'multi'          : true,
		'onError'        : function(event, queueID, fileObj, errorObj){
			                     alert(errorObj)  
                           //displayAttachments(fileObj, response);
                         },
		'onComplete'     : function(event, queueID, fileObj, response, data){		                     
                           displayAttachments(fileObj, response,'file');
                         }
	});  	
}
function uplodifyPhoto(){

	$j("#uploadify_photo").uploadify({
		'uploader'       : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/uploadify.swf',
		'script'         : CONTROLLER_URL+'/index.php?r=admin/buildinginfo/uploadyfy/file_type/photo',
		'cancelImg'      : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/cancel.png',
		'folder'         : '',
		'queueID'        : 'photofileQueue',
		'buttonText'     : 'Allega Foto',
		'wmode'          : 'transparent',
		'auto'           : true,
		'multi'          : true,
		'onError'        : function(event, queueID, fileObj, errorObj){
			                     alert(errorObj)  
                           //displayAttachments(fileObj, response);
                         },
		'onComplete'     : function(event, queueID, fileObj, response, data){		                     
                           displayAttachments(fileObj, response,'photo');
                         }
	});   
}
function uplodifySWF(){

	$j("#uploadify_swf").uploadify({
		'uploader'       : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/uploadify.swf',
		'script'         : CONTROLLER_URL+'/index.php?r=admin/buildinginfo/uploadyfy/file_type/swf',
		'cancelImg'      : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/cancel.png',
		'folder'         : '',
		'queueID'        : 'swffileQueue',
		'buttonText'     : 'Allega Flash 360',
		'wmode'          : 'transparent',
		'auto'           : true,
		'multi'          : true,
		'onError'        : function(event, queueID, fileObj, errorObj){
			                     alert(errorObj)  
                           //displayAttachments(fileObj, response);
                         },
		'onComplete'     : function(event, queueID, fileObj, response, data){
                           displayAttachments(fileObj, response,'swf');
                         }
	});   
}
function uplodifyVideo(){

	$j("#uploadify_video").uploadify({
		'uploader'       : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/uploadify.swf',
		'script'         : CONTROLLER_URL+'/index.php?r=admin/buildinginfo/uploadyfy/file_type/video',
		'cancelImg'      : CONTROLLER_URL+'/scripts/jquery/jquery.uploadify-v2.1.0/cancel.png',
		'folder'         : '',
		'queueID'        : 'videofileQueue',
		'buttonText'     : 'Allega Video',
		'wmode'          : 'transparent',
		'auto'           : true,
		'multi'          : true,		
		'onError'        : function(event, queueID, fileObj, errorObj){
			                     alert(errorObj)  
                           //displayAttachments(fileObj, response);
                         },
		'onComplete'     : function(event, queueID, fileObj, response, data){		                     
                           displayAttachments(fileObj, response,'video');
                         }
	});   
}
function displayAttachments(fileObj, response,attachType)
{   
	 response = response +":"+UPLOADED_FILES_INDEX
   UPLOADED_FILES[UPLOADED_FILES_INDEX] = response;
   UPLOADED_FILES_INDEX++;
   //alert(response);
   var item = "";
   item += "<div id='"+response+"' style='border:0px solid #cccddd; width:70%; border-bottom:0px solid #cccddd; padding-top:7px;'>";
   //item += "<div id='test' style='border:0px solid #cccddd; width:70%; border-bottom:0px solid #cccddd; padding-top:7px;'>";
      item += "<div style='float:left;'>";
         //item += "<input type='radio' id='cover_image_"+UPLOADED_FILES_INDEX+"' onclick='clearothercovers("+UPLOADED_FILES_INDEX+")' name='cover_image_"+UPLOADED_FILES_INDEX+"' value='Yes'>immagine di copertina&nbsp;<img src='"+CONTROLLER_URL+"/images/attach.png' border='0' />";
      
 item += "<img src='"+CONTROLLER_URL+"/images/attach.png' border='0' />";	  item += "</div>";
      item += "<div style='float:left;'>"+fileObj.name+"</div>";
      item += "<div style='float:left;'>";
      item += "<img src='"+CONTROLLER_URL+"/images/cross.png' border='0' style='cursor:pointer;' onclick=\"removeAttachment('"+response+"')\" />";
      item += "</div>";
      item += "<div style='clear:both;'></div>";
   item += "</div>";
   
   var html = $j('#uploaded_'+attachType+'_list').html() + item;
   
   $j('#uploaded_'+attachType+'_list').html(html);
}

function removeAttachment(_file)
{  
   if(!_file)
   {
      return false;   
   }
   
   _list = new Array();
   _index = 0;
   for(i=0; i < UPLOADED_FILES.length; i++)
   {
      if(UPLOADED_FILES[i] != _file)
      {
         _list[_index] = UPLOADED_FILES[i];
         _index++;
      }
   }
   
   UPLOADED_FILES = _list
   UPLOADED_FILES_INDEX = _index;
   
   var _container = document.getElementById('uploaded_file_list');
   var _item = document.getElementById(_file);
   _container.removeChild(_item);
      
   var _url = CONTROLLER_URL + "/index.php?r=admin/buildinginfo/removeuploadedfile";
   
   var _data = "file=" + _file;
   
   $j.ajax({
      type: 'post',
      url: _url,
      data: _data,
      dataType: 'json',
      async: false,
      success: function(json)
      {
         
      }
   });
}
function deleteAttachment(_filetype, _attachmentid, _buildingid)
{
   if(!_attachmentid)
   {
      return false;   
   }     
      
   var _url = CONTROLLER_URL + "/index.php?r=admin/buildinginfo/deleteuploadedfile";
   
   var _data = "attachment_id=" + _attachmentid;
   
   $j.ajax({
      type: 'post',
      url: _url,
      data: _data,
      dataType: 'json',
      async: false,
      success: function(json)
      {
         $j("#attachment"+_attachmentid).html("");
      }
   });
}
var basicSearchHTML = '';
var advSearchHTML = '';
function showAdvancedSearch()
{
	$j("#basic_search").hide();
	//basicSearchHTML = $j("#basic_search").innerHTML;
	//$j("#basic_search").innerHTML = "";
	$j("#advance_search").show();	
}
function showBasicSearch()
{
	$j("#advance_search").hide();	
	//advSearchHTML = $j("#advance_search").innerHTML;
	//$j("#advance_search").innerHTML = "";
	$j("#basic_search").show();
}
function checkPrivacy(itemObj)
{
	if($j(itemObj).is(':checked')) {
            $j('#submitter').removeAttr('disabled');		
         }
         else
         	{
         		$j('#submitter').attr('disabled','disabled');		
         	}
}
function openDocument(openUrl)
{
	var load = window.open(openUrl,'','scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}
