var objMap;
var map;
var objGeoCoder;
function initialize() {
    var myLatlng;
    var Lat = $('#lat').val();
    var Lng = $('#lng').val();
    var iZoomLevel;    
    if(Lat && Lng){
        myLatlng = new google.maps.LatLng(Lat, Lng);
        iZoomLevel = 14;        
    }
    else{
    myLatlng = new google.maps.LatLng(19.55979, -71.861572);
        iZoomLevel = 9;    
    }
    var myOptions = {
        zoom: iZoomLevel,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    }
    objMap = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    locationMarker = new google.maps.Marker({
        map : objMap,
        animation : google.maps.Animation.drop,
        position :  myLatlng
    });
    
    google.maps.event.addListener(objMap, 'rightclick', function () {
        var sLatLng = new String(objMap.getCenter());
        var arrLatLng = sLatLng.split(',');
        var marker = new google.maps.Marker({
            position: objMap.getCenter(),
            map: objMap
        });
        sLatitude = arrLatLng[0].replace('(', '');
        sLongitude = arrLatLng[1].replace(')', '');
        $('#lat').val(sLatitude);
        $('#lng').val(sLongitude);
    });
}
function mapINIT() {
    var myLatlng;
    var Lat = $('#lat').val();
    var Lng = $('#lng').val();
    var iZoomLevel;    
    if(Lat && Lng){
        myLatlng = new google.maps.LatLng(Lat, Lng);
        iZoomLevel = 14;        
    }
    else{
    myLatlng = new google.maps.LatLng(19.55979, -71.861572);
        iZoomLevel = 9;    
    }
    var myOptions = {
        zoom: iZoomLevel,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
    }
    objMap = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    locationMarker = new google.maps.Marker({
        map : objMap,
        animation : google.maps.Animation.drop,
        position :  myLatlng
    });

    var contentString = document.getElementById('_title').value;
        
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    google.maps.event.addListener(locationMarker, 'click', function() {
      infowindow.open(objMap,locationMarker);
    });    
    
 
    
}
function addMarker(location) {
    marker = new google.maps.Marker({
        position: location,
        map: objMap
    });
    markersArray.push(marker);
}
function removeTempImage(sImage,sDivID){
    $.get(sJSBaseURL+'my_account/requestRemoveImage/'+sImage+'/temp/', function(data) {
        if(data == 1){
            $('#'+sDivID).remove();
            alert('Image deleted');
        }
        else{
            alert('Image can not be deleted,please try again later.');
        }
    });
}
function removeImage(sImage,sDivID,iID){
    $.get(sJSBaseURL+'my_account/requestRemoveImage/'+sImage+'/original/'+iID, function(data) {
        if(data == 1){
            $('#'+sDivID).remove();
            alert('Image deleted');
        }
        else{
            alert('Image can not be deleted,please try again later.');
        }
    });   
}
function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
    return randomstring;
}
$(document).ready(function () {
/*	$('#srch_location').click(function(){
	   $.get(sJSBaseURL+'realestate/suggest',function(data){
	       $('#suggestTable').html(data);
	   });
	});
*/

    $('#movers-row a[href][title]').qtip({
        content: {
            text: false 
        },
       
        style: 'blue'
         
        
    });
    $('input.has_tip').qtip({
        content: {
            text: false 
        },
        position: {
          corner: {
             tooltip: 'leftMiddle',
             target: 'rightMiddle'
          }
        },         
        style: 'green' 
    }); 
    $('textarea.has_tip').qtip({
        content: {
            text: false 
        },
        position: {
          corner: {
             tooltip: 'leftMiddle',
             target: 'rightMiddle'
          }
        },         
        style: 'green' 
    });        
     $('#srch_location').qtip({
        content: {
            text: false 
        },
        style: 'blue' ,
          position: {
      corner: {
         target: 'topMiddle',
         tooltip: 'bottomMiddle'
      }
   }
    });  
var theInt = null;
		var $crosslink, $navthumb;
		var curclicked = 0;
		var iInterVal = 4000;
		theInterval = function(cur){
			clearInterval(theInt);
			
			if( typeof cur != 'undefined' )
				curclicked = cur;
			
			$crosslink.removeClass("active-thumb");
			$navthumb.eq(curclicked).parent().addClass("active-thumb");
				$(".stripNav ul li a").eq(curclicked).trigger('click');
                iInterval = 10000;
			
			theInt = setInterval(function(){
				$crosslink.removeClass("active-thumb");
				$navthumb.eq(curclicked).parent().addClass("active-thumb");
				$(".stripNav ul li a").eq(curclicked).trigger('click');
				curclicked++;
				if( 12 == curclicked )
					curclicked = 0;
				
			}, iInterVal);
		};
		
		$(function(){
			if ($("#main-photo-slider").length) $("#main-photo-slider").codaSlider();
			
			$navthumb = $(".nav-thumb");
			$crosslink = $(".cross-link");
			
			$navthumb
			.click(function() {
				var $this = $(this);
				theInterval($this.parent().attr('href').slice(1) - 1);
				return false;
			});
			
			theInterval();
		});
     
     
    $('#featured').show();
    $('#preLoader').hide();
    if ($('.listItemImages').length) $('.listItemImages').popeye();
    if ($('#slidermask').length) $('#slidermask').carousel('.slideleft', '.slideright',{min:3}); 
    $('.default-value').each(function() {
        var default_value = this.value;
        $(this).css('color', '#666'); // this could be in the style sheet instead
        $(this).focus(function() {
            if(this.value == default_value) {
                this.value = '';
                $(this).css('color', '#333');
            }
        });
        $(this).blur(function() {
            if(this.value == '') {
                $(this).css('color', '#666');
                this.value = default_value;
            }
        });
    });
	//$(function(){
    
    $('select[id="country_id"]').change(function() {
        $.getJSON(sJSBaseURL + "realestate/getRegionsByCountry/" + $(this).val(), {
            id: $(this).val()
        }, function (j) {
            var options = '';
            options += '<option>'+sRegionSelect+'</option>';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
            }
            $('select[id="region_id"]').html(options);
            $('select[id="region_id"] option:first').attr('selected', 'selected');
        })
    });
    $('select[id="region_id"]').change(function () {
        $.getJSON(sJSBaseURL + "realestate/getCitiesByRegion/" + $(this).val(), {
            id: $(this).val()
        }, function (j) {
            var options = '';
            options += '<option>'+sCitySelect+'</option>';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
            }
            $('select[id="city_id"]').html(options);
            $('select[id="city_id"] option:first').attr('selected', 'selected');
        })
    });			
    $(".srch_type").click(function () {
        var options = '';
        if ($(this).val() == 2) {
            options += '<option>Rent price</option>';
        } else if ($(this).val() == 1) {
            options += '<option>Sell price</option>';
        } else {
            options += '<option>Price</option>';
        }
	    $.getJSON(sJSBaseURL + "realestate/getRentPrices/" + $(this).val(), {
            id: $(this).val()
        }, function (j) {
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
            }
	        $('select[id="price"]').html(options);
	        $('select[id="price"] option:first').attr('selected', 'selected');
        });
    });			
			
		//})();
        $('ul.display li').hover(function(){
            $(this).addClass('li_hover');
        },
        function(){
            $(this).removeClass('li_hover');
        });
        if(typeof uploadify == 'function'){
            $("#upload").uploadify({
          uploader: sJSBaseURL + '/addons/themes/caribe24/swf/uploadify.swf',
          script: sJSBaseURL + 'my_account/addImages',
          cancelImg: sJSBaseURL + '/addons/themes/caribe24/img/cancel.png',
          folder: '/uploads/',
          scriptAccess: 'always',
          multi: true,
          auto: true,
          fileExt: '*.jpg;*.JPG',
          'onError': function (a, b, c, d) {
              if (d.status == 404) alert('Could not find upload script.');
              else if (d.type === "HTTP") alert('error ' + d.type + ": " + d.status);
              else if (d.type === "File Size") alert(c.name + ' ' + d.type + ' Limit: ' + Math.round(d.sizeLimit / 1024) + 'KB');
              else
              alert('error ' + d.type + ": " + d.text);
          },
          'onComplete': function (event, queueID, fileObj, response, data) {
              //Post response back to controller
              $.post(sJSBaseURL + 'my_account/addImages', {
                  filearray: response
              }, function (info) {
                  var randomID = randomString();
                  $("#target").append('<div class="image_div_upload" id="' + randomID + '"><input type="hidden" name="file[]" value="' + response + '" /><img width="150" src="' + sJSBaseURL + 'uploads/temp/' + response + '" /><br /><a href="javascript:removeTempImage(\'' + response + '\',\'' + randomID + '\')">Remove Image</a></div>');
              });
          }
      });  
      }
});
jQuery.fn.carousel = function(previous, next, options){
	var sliderList = jQuery(this).children()[0];
	if (sliderList) {
		var increment = jQuery(sliderList).children().outerWidth("true"),
		elmnts = jQuery(sliderList).children(),
		numElmts = elmnts.length,
		sizeFirstElmnt = increment,
		shownInViewport = Math.round(jQuery(this).width() / sizeFirstElmnt),
		firstElementOnViewPort = 1,
		isAnimating = false;
		if ((typeof options == "undefined ") && (typeof options.min == "undefined ")) { options.min = 3}
		if (elmnts.length > options.min) {
			for (i = 0; i < shownInViewport; i++) {
				jQuery(sliderList).css('width', (numElmts + shownInViewport) * increment + increment + "px");
				jQuery(sliderList).append(jQuery(elmnts[i]).clone());
			}
			jQuery(previous).click(function(event){
				if (!isAnimating) {
					if (firstElementOnViewPort == 1) {
						jQuery(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
						firstElementOnViewPort = numElmts;
					}
					else {
						firstElementOnViewPort--;
					}
					jQuery(sliderList).animate({
						left: "+=" + increment,
						y: 0,
						queue: true
					}, "swing", function(){
						isAnimating = false;
					});
					isAnimating = true;
				}
			});
			jQuery(next).click(function(event){
				if (!isAnimating) {
					if (firstElementOnViewPort > numElmts) {
						firstElementOnViewPort = 2;
						jQuery(sliderList).css('left', "0px");
					}
					else {
						firstElementOnViewPort++;
					}
					jQuery(sliderList).animate({
						left: "-=" + increment,
						y: 0,
						queue: true
					}, "swing", function(){
						isAnimating = false;
					});
					isAnimating = true;
				}
			});
		} else {
			jQuery(next).css("display","none");
			jQuery(previous).css("display","none");
		}
	}
};
