// JavaScript Document
var MLSNumberArray;
var CurrentPosition = 0;
var AgentKEY;
var AgentUserID;
var RecordType = 120;
var Template;
var TotalListing = 0;
var BoardArray = new Array();


    Array.prototype.unique = function( b ) {
     var a = [], i, l = this.length;
     for( i=0; i<l; i++ ) {
      if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
     }
     return a;
    };

	$().ready(function(){
        AgentKEY = $('#AgentKEY').val();
        //AgentUserID = $('#AgentUserID').val();
		newGetAgentListing();
		//agentPredefinedSearchCheck();
		//agentPredefinedSearch();
		
        //DataFloat.Agora.Util.AutoComplete('mlsnumber', '0110', '120');
        //DataFloat.Agora.Util.AutoComplete('subdivision', '1171', '120', null, null, 200);		
   	})


    function newGetAgentListing()
    {
        
        if ($("#divFeaturedProperty").size())
        {
            var params = "HtmlInterface=TransformToJSON&RecordType=14&n_dt=0&0070=4&n_uc="+AgentKEY;
            
            var oAjaxManager = new DataFloat.Agora.AjaxManager(params);
                oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerCount, 1, function(msg){
                     //If there is no listing from this agent, we randomly pick one (may need to change this logic)
                    if ($.trim(msg)==0){
                        return false;
						params = "HtmlInterface=TransformToJSON&RecordType=120&Agora__ItemPerPage=10&fld_0110=MLSNum&5020_min=300000&5020_max=350000&order=random";
                    }else{
			            params = "HtmlInterface=TransformToJSON&RecordType=14&n_dt=0&0070=4&n_uc="+AgentKEY + "&fld_0030=MLSNum&fld_0020=Board&order=random";
                    }
                    oAjaxManager.ItemPerPage = 15;
                    oAjaxManager.FormParams =params;
                    oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerGetContentJSON, 1, function(msg){
                        MLSNumberArray = JSON.parse(msg);
                        TotalListing = MLSNumberArray.length;
                        renderFeatureProperty();
                    })
            })
         }
    }

    function renderFeatureProperty()
    {
        getUniqueBoard();
		HtmlInterface = "AgentSiteFeatureProperty_Template" + MLSNumberArray[CurrentPosition].Board;//+Template;    
		/*if (MLSNumberArray[CurrentPosition].Board=="140")
		    AspNet_formParams = "HtmlInterface=" + HtmlInterface + "&RecordType=" + MLSNumberArray[CurrentPosition].Board + "&0113_exc="+MLSNumberArray[CurrentPosition].MLSNum;
        else*/ 
        if (MLSNumberArray[CurrentPosition].Board=="180")
		    AspNet_formParams = "HtmlInterface=" + HtmlInterface + "&RecordType=" + MLSNumberArray[CurrentPosition].Board + "&0115_exc="+MLSNumberArray[CurrentPosition].MLSNum;		    
		else AspNet_formParams = "HtmlInterface=" + HtmlInterface + "&RecordType=" + MLSNumberArray[CurrentPosition].Board + "&0110_exc="+MLSNumberArray[CurrentPosition].MLSNum;
        var oAjaxManager = new DataFloat.Agora.AjaxManager(AspNet_formParams, 'divFeaturedProperty');
            oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerCount, 1, function(msg){
                
                //If there is no listing from this agent, we randomly pick one (need to change this logic)
				oAjaxManager.ItemPerPage = 1;
				oAjaxManager.Call(hideShowLinks, null, null, null, DataFloat.Agora.Services.ServiceContentManagerMultipleHtml, "allcontent");
            })
    }

    function getUniqueBoard()
    {
        
        for (var i=0; i<MLSNumberArray.length; i++)
        {

            BoardArray[i] = MLSNumberArray[i].Board;
        }
        BoardArray = BoardArray.unique();
    }
    
    function NextFeatureProperty(index)
    {
        CurrentPosition += parseInt(index);
        if (CurrentPosition>=TotalListing) CurrentPosition = 0;
        else if (CurrentPosition<=0) CurrentPosition = TotalListing-1;
        renderFeatureProperty();
    }


//****************************************************************************
// Check if agent hosts any active listing
//****************************************************************************
	function agentListingCheck()
	{
	    var Template = $('#Template').val();

		if ($('#propertyDetails_'+Template).size())
		{
            var AgentKEY = $('#AgentKEY').val();
            var MLSAllow = $('#MLSAllow').val();
            var AgentUserID = $('#AgentUserID').val();	
			var RecordType = MLSAllow;
			var HtmlInterface = "AgentSiteFeatureProperty_"+Template;
			
			var AspNet_formParams = "HtmlInterface=" + HtmlInterface + "&RecordType=" + RecordType + "&agentkey=" + AgentKEY + "&4370="+AgentUserID;

            var oAjaxManager = new DataFloat.Agora.AjaxManager(AspNet_formParams);
                oAjaxManager.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerCount, 1, function(msg){
                    
                    //If there is no listing from this agent, we randomly pick one (need to change this logic)
                    if ($.trim(msg)==0)
						AspNet_formParams = "HtmlInterface=" + HtmlInterface + "&RecordType=" + RecordType + "&0001=2&5020_min=500000&agentkey="+AgentKEY;
						
                    oAjaxManager.DivResult = "propertyDetails_"+Template;
                    oAjaxManager.FormParams = AspNet_formParams
					oAjaxManager.ItemPerPage = 1;
					oAjaxManager.Call(hideShowLinks, null, null, null, DataFloat.Agora.Services.ServiceContentManagerMultipleHtml, "allcontent");
                })
		}
	}
	
	function hideShowLinks()
	{
	    var AgentEP = $("#AgentEP").val();
	    if (AgentEP) $("EPLOGO").show();
	}
	
	//Check if there is predefined agent search -- Enable the drop down
	function agentPredefinedSearchCheck()
	{
	    var AgentKEY = $('#AgentKEY').val();
	    var params = "RecordType=9&Agora__ItemPerPage=1&n_dt=0&n_uc=" + AgentKEY;
        var oAjaxManager2 = new DataFloat.Agora.AjaxManager(params);
            oAjaxManager2.NewSystemRequest(DataFloat.Agora.Services.ServiceContentManagerCount, 1, function(msg){
                if ($.trim(msg)!=0)
                    $("#MySearchLi").show();
            })
        	
	}
	
	// Generate agent Predefined Content
	function agentPredefinedSearch()
	{
	    if ($('#PredefinedSearchDiv').size())
	    {
            var AgentKEY = $('#AgentKEY').val();
            var MLSAllow = $('#MLSAllow').val();
            var AgentUserID = $('#AgentUserID').val();	
		    var RecordType = MLSAllow;
		    var PredefinedHtmlInterface = "AgentPredefinedSearchList";
			
		    var AspNet_formParams = "HtmlInterface=" + PredefinedHtmlInterface + "&RecordType=9&n_dt=0&n_uc=" + AgentKEY;

            //If there is no listing from this agent, we randomly pick one (need to change this logic)
		    var oAgentPSSearch = new DataFloat.Agora.AjaxManager(AspNet_formParams, "PredefinedSearchDiv" , "");
		    oAgentPSSearch.ItemPerPage = 1;
		    oAgentPSSearch.Call(null, null, null, null, DataFloat.Agora.Services.ServiceContentManagerMultipleHtml, "allcontent");
		}
	}
	
	function ViewAllMyProperties()
	{
		AgentUserID = $('#AgentUserID').val();
		window.location.href = "/SearchResult.aspx?get=1&4370=" + AgentUserID + "&agentkey="+AgentKEY+"&template="+Template;;
	}

	function QuickSearchSubmit(formID)
	{
		if ($('#0110').val()==$("#0110").attr("title")) $("#0110").val('');
		if ($('#1050').val()==$("#1050").attr("title")) $("#1050").val('');
		if ($('#4010').val()==$("#4010").attr("title")) $("#4010").val('');
		var params = serializeForm(formID);
	    var fragment = $.param( params );
		$("#"+formID).submit();
	}


	function gotoDetailFromOffice(k, PT)
	{
		linkTo(DOCUMENT_ROOT + '/detail.php?k=' + k + '&PT=' + PT + '&From=Office');
		$('#linkIframe').show();
		$('#columns').hide();
	}
	function submitSearch()
	{
		$('#QuickSearch').attr('target','searchIframe');
		$('#searchIframe').show();
		$('#ContentBody').hide();
	}
	function CheckAgentName()
	{
		var AgentName = $('#agentname').val();
		if (trim(AgentName)=='' || AgentName==' Agent Name')
		{
			linkTo(DOCUMENT_ROOT + '/AgentSearch.php');
			$('#linkIframe').show();
			$('#columns').hide();
			return false;
		}else
		{
			$('#linkIframe').show();
			$('#columns').hide();
			return true;
		}
	}
	function linkTo(URL)
	{
		$('#linkIframe').attr('src',URL);
		$('#linkIframe').show();
		$('#columns').hide();
	}
	
	function contactMeValidation()
	{
		if ($.trim($('#txtName').val())=='')
		{
			alert('Please fill the required field.');
			$('#txtName').focus();
			return false;
		}
		if ($.trim($('txtEmail').val())=='')
		{
			alert('Please fill the required field.');
			$('#txtEmail').focus();
			return false;
		}
		if ($.trim($('#AgentEmail').val())=='')
		{
			alert('Email cannot be sent because agent e-mail is not setup yet.');
			return false;
		}
		return true;
	}
	
	function hideMPKIframe()
	{
		$('#MPKIframe').hide();
	}
	
	function displayMPKIframe(url)
	{

		if ($('#linkIframe').size())
		{
			$('#linkIframe').attr('src',url);
			$('#linkIframe').show();
			$('#MPKIframe').hide();
		}
		else 
		{
			$('#bodyContent').hide();
			$('#MPKIframe').attr('src',url);
			$('#MPKIframe').show();
		}
	}
	
	function gotoContact()
	{
		window.location.href = $('#ContactMe').attr('href');
	}

	function frameOutPage(URL)
	{
		if ($('#linkIframe').size()==0)
		{
			iframeElement = '<iframe src="'+URL+'" frameborder="0" id="linkIframe" style="width:100%; height:700px; border:none;" scrolling="no" class="autoHeight"></iframe>';
			$('#contentArea').html(iframeElement);
		}else $('#linkIframe').attr('src',URL);
	}

	function renderAgentQuickSearch(formID)
	{
		if ($('#linkIframe').size()==0)
		{
			iframeElement = '<iframe src="'+DOCUMENT_ROOT+'/contentPage.php?content=searchResults" frameborder="0" id="linkIframe" name="linkIframe" style="width:100%; height:700px;" scrolling="no" class="autoHeight"></iframe>';
			$('#contentArea').html(iframeElement);
		}
		$('#'+formID).attr('target','linkIframe');
		return true;
	}
	function viewMyListing(ID)
	{
		var URL = $('#'+ID).attr('href');
		window.location.href = URL;
	}
	
    function ViewPropertyDetails(MLSNum, PT){
       window.location.href='/PropertyDetail.aspx?searchType=FP&RecordType='+PT+'&Agora__Item__Detail='+MLSNum+'&AgentKEY='+AgentKEY;
	   //var VELatLong = oMap.VirtualMap.GetMapView()
       //if (DataFloat.Agora.Util.GetParameter(oPropertySearch.FormParams, '1180_min')==undefined || DataFloat.Agora.Util.GetParameter(oPropertySearch.FormParams, '1180_min')=="" )
       //oPropertySearch.FormParams += "&1180_min=" + VELatLong.BottomRightLatLong.Latitude.toFixed(12) + "&1180_max=" + VELatLong.TopLeftLatLong.Latitude.toFixed(12) + "&1190_min=" + VELatLong.TopLeftLatLong.Longitude.toFixed(12) + "&1190_max=" + VELatLong.BottomRightLatLong.Longitude.toFixed(12);
       //oPropertySearch.FormParams = DataFloat.Agora.Util.ReplaceQueryString(oPropertySearch.FormParams, "ZoomLevel", oMap.VirtualMap.GetZoomLevel());
  	   //oPropertySearch.SeeDetails(item, DataFloat.Agora.Services.OnSubmitDetailPage);
  	}

	function renderAllMyListingsLink()
	{
	    if (BoardArray.length==1)
	    {
	        $('#divViewMyListing').html("<a href='javascript:viewMyListing("+BoardArray[0]+")'>View All My Listings</a>");
	    }else if (BoardArray.length>1)
	    {
	        for (var i=0; i<BoardArray.length; i++)
	        {
	            MsgToAdd = ""
	            if (BoardArray[i]=="120")
	               MsgToAdd = "<a href='javascript:viewMyListing("+BoardArray[i]+")'>View All My Charlotte Listings</a>";
    	        else if (BoardArray[i]=="140")
	               MsgToAdd = "<a href='javascript:viewMyListing("+BoardArray[i]+")'>View All My Triad Listings</a>";
                else if (BoardArray[i]=="160")
	               MsgToAdd = "<a href='javascript:viewMyListing("+BoardArray[i]+")'>View All My Rock Hill/York SC Listings</a>";
	            else if (BoardArray[i]=="180")
	               MsgToAdd = "<a href='javascript:viewMyListing("+BoardArray[i]+")'>View All My Triangle Listings</a>";	               
	            
	            $('#divViewMyListing').append(MsgToAdd + "<br/>");
	        }
	    }
	}
	
	function viewMyListing(BoardID)
	{
	    window.location.href = "/ResultPage.aspx?JumpSearch=1&get=1&fromFineHome=0&5020_order=descending&RecordType="+BoardID+"&a_k_14_0030_n_uc="+AgentKEY+"&a_k_14_0030_n_dt=0&a_k_14_0030_0020="+BoardID+"&a_k_14_0030_0070=4";
	    //window.location.href = "/ProcessPredefinedSearch.aspx?PDS=AL&RK="+AgentKEY+"&RecordType="+BoardID;
	}