var marketInformation = {
    canBuy: false,
    canSell: false,
    generateLicenceList: function(clientId) {
        this.xmlSubProps = this.ajaxPropertySelectOnSubRegion(clientId);
        var jqProps = $(this.xmlSubProps).find("properties item");
        var tagProp = $("#licenceSelectionBox SELECT[name='property']");
        tagProp.children().remove();
        var button = $("#licenceSelectionBox #goAfterLicenceSelection");
        button.unbind("click");
        if(jqProps.length==0) {
            tagProp.append("<option value=''>NONE</option>");
            tagProp.attr("disabled","true");
            return;
        }
        if(jqProps.length>1) {
            tagProp.append("<option value=''>PLEASE SELECT</option>");
            tagProp.change(function(){
                var id = Number($(this).val());
                var button = $("#licenceSelectionBox #goAfterLicenceSelection");
                button.unbind("click");
                if(id>0) {
                    button.attr("subPropId",id);
                    button.click(function(){
                        marketInformation.ajaxUpdateSubPropId($(this).attr("subPropId"));
                        location = marketInformation.latestRedirect;
                    });
                } else {
            }
            });
        } else {
            button.unbind("click");
            button.attr("subPropId",$(jqProps[0]).attr("id"));
            button.click(function(){
                marketInformation.ajaxUpdateSubPropId($(this).attr("subPropId"));
                location = marketInformation.latestRedirect;
            });
        }
        tagProp.removeAttr("disabled");
        for(var i=0; i<jqProps.length; i++) {
            var id =$(jqProps[i]).attr("id");
            var name = $(jqProps[i]).attr("name");
            tagProp.append("<option value='"
                +id+"'>"+name+"</option>");
        }
    },
    redirectOnSelectLic: function(redirect,isBuy){
        var button = $("#licenceSelectionBox #goAfterLicenceSelection");
        button.unbind("click");
        this.latestRedirect = redirect;
        if (this.ajaxSubProperty()<=0) {
            this.xmlClients = this.ajaxClientSelectOnSubRegion();
            var jqClients = $(this.xmlClients).find("clients item");
            var tagCl = $("#licenceSelectionBox SELECT[name='client']");
            var tagProp = $("#licenceSelectionBox SELECT[name='property']");
            tagCl.children().remove();
            tagProp.children().remove();
            tagProp.append("<option value=''>NONE</option>");
            tagProp.attr("disabled","true");
            if(jqClients.length<=0) {
                alert("You have no licence set up for this market region. ");
                tagCl.append("<option value=''>NONE</option>");
                tagCl.attr("disabled","true");
                return;
            }
            if(jqClients.length==1) {
                var clId = $(jqClients[0]).attr("id")
                if(clId == $("INPUT#wfUserIdField").val())
                    $("#licenceSelectionBox .clientSelection").hide();
                marketInformation.generateLicenceList(clId);
            } else {
                tagCl.append("<option value=''>PLEASE SELECT</option>");
                tagCl.change(function(){
                    marketInformation.generateLicenceList($(this).val());
                });
            }
            tagCl.removeAttr("disabled");
            for(var i=0; i<jqClients.length; i++) {
                var id =$(jqClients[i]).attr("id");
                var name = $(jqClients[i]).attr("name");
                tagCl.append("<option value='"
                    +id+"'>"+name+"</option>");
            }
            $("#licenceSelectionBox").css("opacity","0");
            $("#licenceSelectionBox").show();
            $("#licenceSelectionBox").animate({
                opacity:1.0
            },"normal");
            if(isBuy) {
                $("#licenceSelectionBox .darkgreen").addClass("blue").removeClass("darkgreen");
                $("#licenceSelectionBox .round_corner_green").addClass("round_corner_blue").removeClass("round_corner_green");
                $("#licenceSelectionBox .btn_green").addClass("btn_blue").removeClass("btn_green");
            } else {
                $("#licenceSelectionBox .blue").addClass("darkgreen").removeClass("blue");
                $("#licenceSelectionBox .round_corner_blue").addClass("round_corner_green").removeClass("round_corner_blue");
                $("#licenceSelectionBox .btn_blue").addClass("btn_green").removeClass("btn_blue");
            }
        } else {
            location = redirect;
        }
    },
    attemptToBuy: function(redirect) {

        var validLoginSession = this.isValidLoginSession();
        if(!validLoginSession) {

            // if not logged in then notify the user
            return false;
        } else {

            // if logged in but can't buy then notify the user
            if(!marketInformation.canBuy) {
                alert("You can not buy water parcels from this market. "
                    +"To buy water, select 'Change market' from the green region title bar.");
                return false;
            } else {

                // if logged in and can buy then let them proceed
                this.redirectOnSelectLic(redirect,true);
                return true;
            }
        }
    },
    attemptToSell: function(redirect) {
        
        var validLoginSession = this.isValidLoginSession();
        if(!validLoginSession) {

            // if not logged in then notify the user
            return false;
        } else {

            // if logged in but can't buy then notify the user
            if(!marketInformation.canSell) {
                alert("You can not sell water parcels to this market. "
                    +"To sell water, select 'Change market' from the green region title bar.");
                return false;
            } else {

                // if logged in and can buy then let them proceed
            this.redirectOnSelectLic(redirect,false);
                return true;
            }
        }
           
    },
    ajaxMarketPricing: function (stateId) {
        var result;
        $.ajax({
            type: "post",
            url: "/jsp/ajax/waterMarket-pricing.jsp",
            data: "stateId="+stateId,
            cache: false,
            async: false,
            success: function(xmlData){
                result = xmlData;
            }
        });
        return result;
    },
    ajaxSubProperty: function() {
        var propId = Number($.ajax({
            type: "get",
            url: "/jsf/postback/retrieve-subpropid-wmb.jsf",
            cache: false,
            async: false
        }).responseText);
        return propId;
    },
    ajaxClientSelectOnSubRegion: function() {
        var result;
        $.ajax({
            type: "get",
            url: "/jsf/postback/select-clients-by-subregion.jsf",
            cache: false,
            async: false,
            success: function(xmlData){
                result = xmlData;
            }
        });
        return result;
    },
    ajaxPropertySelectOnSubRegion: function(id) {
        var result;
        $.ajax({
            type: "post",
            url: "/jsf/postback/select-subprop-by-client-subregion.jsf",
            data: "clientId="+ id,
            cache: false,
            async: false,
            success: function(xmlData){
                result = xmlData;
            }
        });
        return result;
    },
    ajaxUpdateSubPropId: function(id) {
        $.ajax({
            type: "get",
            url: "/jsf/postback/update-subpropid-wmb.jsf",
            data: "subPropertyId="+id,
            cache: false,
            async: false
        });
    },
    /**
     * increase the market pricing update from 15000 to 600000
     */
    refreshMarketPricing: function(){
        var xmlPricing = this.ajaxMarketPricing(this.stateId);
        var updated = $(xmlPricing).find("pricing").attr("timeUpdated");
        if(updated!='N|A') {
            var weighted = Number($(xmlPricing).find("pricing weighted").text());
            var median = Number($(xmlPricing).find("pricing median").text());
            if(weighted)
                $("#pricingWeightedAvg").text('$'+weighted.toFixed(2));
            if(median)
                $("#pricingMedian").text('$'+median.toFixed(2));
            $("#pricingUpdateTime").text(updated);
        } else {
            $("#pricingWeightedAvg").text('N|A');
            $("#pricingUpdateTime").text('N|A');
            $("#pricingMedian").text('N|A');
        }
        this.refreshTimer = setTimeout("marketInformation.refreshMarketPricing();", 600000);
    },
    stopRefereshingPricing: function() {
        if(this.refreshTimer!=null) {
            clearTimeout(this.refreshTimer);
            this.refreshTimer = null;
        }
    },
    isValidLoginSession: function() {
        if(Number($("INPUT#wfUserIdField").val()) >0)
            return true;
        alert('Members only. Please login or register to access this function.');
        return false;
    },
    photoFileNamesArray : new Array("dreamstime-960480.jpg",
        "famers-960480.jpg","farmer-computer-960480.jpg", "pivot-960480.jpg" ),

    changePhotos: function () {
        var s1 = Math.floor(Math.random()*4);
        var s2 = (s1+1) % 4;
        $("IMG#imageOccBuyings").attr("src","/images/photos/"+this.photoFileNamesArray[s1]);
        $("IMG#imageOccSellings").attr("src","/images/photos/"+this.photoFileNamesArray[s2]);
    }
};



$(document).ready(function(){
    $(".filled_round_corner_blue").hover(function(){
        $(this).attr('class','filled_round_corner_lightblue');
    },function(){
        $(this).attr('class','filled_round_corner_blue');
    })

    $(".filled_round_corner_green").hover(function(){
        $(this).attr('class','filled_round_corner_darkgreen');
    },function(){
        $(this).attr('class','filled_round_corner_green');
    })

    $("A.underConstruction").click(function(){
        alert("Under construction.","Sorry");
    })

    $("#sellWaterButton").click(function(){
        marketInformation.attemptToSell('/add-order.html?isBuyOrder=false');
    });

    $("#buyWaterButton").click(function(){
        marketInformation.attemptToBuy('/add-order.html?isBuyOrder=true');
    });

    if(Number($("INPUT#wfUserIdField").val()) <=0) {
        $("A[restriction='true']").removeAttr("href");
        $("A[restriction='true']").click(function(){
            marketInformation.isValidLoginSession();
        });
    } else {
    }
});

function onChangeMarket(xmlData,command) {
	
    $("#licenceSelectionBox").hide();
    if(command== 'market') {
        marketInformation.canBuy= false;
        marketInformation.canSell = false;
    }
    
    if(command=='market' || command=='load') {
        var info =$(xmlData).find("selectioninfo");
        
        $("SPAN#regionNameBanner").text(
            info.attr("regionName") + " - " + info.attr("subTypeLabel"));
        marketInformation.stopRefereshingPricing();
        var buyOrSell ="";
        if(info.attr("canBuy")=='true' && info.attr("canSell")!='true') {
            buyOrSell += "You can only buy water parcels from this market. "
            marketInformation.canBuy = true;
        } else if(info.attr("canSell")=='true' && info.attr("canBuy")!='true') {
            buyOrSell += "You can only sell water parcels to this market. "
            marketInformation.canSell = true;
        } else if(info.attr("canSell")=='true' && info.attr("canBuy")=='true'){
            marketInformation.canBuy = true;
            marketInformation.canSell = true;
        } else {
            buyOrSell += "You can not buy or sell water parcel in this market. "
        }
        $("#indicateBuyOrSell").text(buyOrSell);
        if(info.attr("isPerm")=='true') {
            $("#indicateTempOrPerm").text("PERMANENT");
            marketInformation.stateId = '0';
        } else {
            $("#indicateTempOrPerm").text("TEMPORARY");
            marketInformation.stateId = info.attr("stateId");
        }

        $("#indicateLatestAllocation").text(info.attr("allocation"));
        $("#indicateLatestStorage").text(info.attr("storage"));
        marketInformation.refreshMarketPricing();
        if(command== 'market') {
            window.location.reload();
        }
    //window.location.reload();
    }
}

function onChangeMarket_homepage(xmlData,command) {
    
    $("#licenceSelectionBox").hide();
    if(command== 'market') {
        location.replace("/jsf/water-market.jsf");
        marketInformation.canBuy= false;
        marketInformation.canSell = false;
    }

    if(command=='market' || command=='load') {
        var info =$(xmlData).find("selectioninfo");
        $("SPAN#regionNameBanner").text(
            info.attr("regionName") + " - " + info.attr("subTypeLabel"));
        marketInformation.stopRefereshingPricing();
        var buyOrSell ="";
        if(info.attr("canBuy")=='true' && info.attr("canSell")!='true') {
            buyOrSell += "You can only buy water parcels from this market. "
            marketInformation.canBuy = true;
        } else if(info.attr("canSell")=='true' && info.attr("canBuy")!='true') {
            buyOrSell += "You can only sell water parcels to this market. "
            marketInformation.canSell = true;
        } else if(info.attr("canSell")=='true' && info.attr("canBuy")=='true'){
            marketInformation.canBuy = true;
            marketInformation.canSell = true;
        } else {
            buyOrSell += "You can not buy or sell water parcel in this market. "
        }
        $("#indicateBuyOrSell").text(buyOrSell);
        if(info.attr("isPerm")=='true') {
            $("#indicateTempOrPerm").text("PERMANENT");
            marketInformation.stateId = '0';
        } else {
            $("#indicateTempOrPerm").text("TEMPORARY");
            marketInformation.stateId = info.attr("stateId");
        }

        $("#indicateLatestAllocation").text(info.attr("allocation"));
        $("#indicateLatestStorage").text(info.attr("storage"));
        marketInformation.refreshMarketPricing();
    }
}

function processTradeNow(index, type) {
    if(type=='SELL_ORDER') {
        marketInformation.attemptToBuy('/user-process-order.html?orderRegionId=' + index);
    } else if (type=='BUY_ORDER'){
        marketInformation.attemptToSell('/user-process-order.html?orderRegionId=' + index);
    } else {
        marketInformation.attemptToBuy('/offer-tender.html?offeridx=' + index);
    }
}

function onRetrieveBuyings(xmlMarketData) {
    
    var totalVolume = 0;
    var parcels = $(xmlMarketData).find("parcel");
    for (i = 0; i < parcels.length; i++){
        totalVolume = totalVolume + Number(parcels[i].getAttribute('quantity'));
    }

    $("#licenceSelectionBox").hide();
    if(parcels.length>0) {
        $("#imageOccBuyings").animate({
            opacity:0.0
        },"normal",function(){
            $(this).hide();
            $("#marketDataBuyings").show();
            $("#marketDataBuyings").animate({
                opacity:1.0
            },"normal");
        });
        $(".buyDataHint").show();
        $(".noBuyDataHint").hide();
    } else {
        $("#marketDataBuyings").animate({
            opacity:0.0
        },"normal",function(){
            $(this).hide();
            $("#imageOccBuyings").css("opacity","0.0");
            marketInformation.changePhotos();
            $("#imageOccBuyings").show();
            $("#imageOccBuyings").animate({
                opacity:1.0
            },"normal");
        });
        $(".buyDataHint").hide();
        $(".noBuyDataHint").show();
    }
    $("#numberOfBuyParcels").text(parcels.length);
    $("#numberOfBuyVolumes").text(totalVolume.toFixed(2));
}

function onRetrieveSellings(xmlMarketData) {
    var totalVolume = 0;
    var parcels = $(xmlMarketData).find("parcel");
    for (i = 0; i < parcels.length; i++){
        totalVolume = totalVolume + Number(parcels[i].getAttribute('quantity'));
    }
    $("#licenceSelectionBox").hide();
    if(parcels.length>0) {
        $("#imageOccSellings").animate({
            opacity:0.0
        },"normal",function(){
            $(this).hide();
            $("#marketDataSellings").show();
            $("#marketDataSellings").animate({
                opacity:1.0
            },"normal");
        });
        $(".sellDataHint").show();
        $(".noSellDataHint").hide();
    } else {
        $("#marketDataSellings").animate({
            opacity:0.0
        },"normal",function(){
            $(this).hide();
            $("#imageOccSellings").css("opacity","0.0");
            marketInformation.changePhotos();
            $("#imageOccSellings").show();
            $("#imageOccSellings").animate({
                opacity:1.0
            },"normal");
        });
        $(".sellDataHint").hide();
        $(".noSellDataHint").show();
    }
    $("#numberOfSellParcels").text(parcels.length);
     $("#numberOfSellVolumes").text(totalVolume.toFixed(2));
}

