var cookiePropertyName = "listOfProperties";

ApplicationState = function(stateData, bookmarkValue) {
    this.stateData = stateData;
    this.changeUrl = bookmarkValue || false;
}

dojo.extend(ApplicationState, {
    back: function() {
        this.changeStateData(this.stateData);
    },
    forward: function() {
        this.changeStateData(this.stateData);
    },
    changeStateData: function(link) {
        eval("searchProperty" + link);
    }
});

function propertyInTheListAlready(propertyId)
{
    var i;
    var cookieValue = dojo.cookie(cookiePropertyName);
    var listOfProperty;

    if (cookieValue != null)
    {
         listOfProperty = cookieValue.split(",");
        for (i=0;i<listOfProperty.length;i++)
        {
            if (parseInt(listOfProperty[i]) == parseInt(propertyId))
                return true;
        }
    }
    return false;
}

function setDefaultPropertyCookie(inputValue)
{
    dojo.cookie(cookiePropertyName, inputValue, {expires: 10080, path: "/"});
}

function saveProperty(propertyId)
{
    var cookieValue = dojo.cookie(cookiePropertyName);
    if ((cookieValue != null) && (cookieValue != ''))
        cookieValue = cookieValue + "," + propertyId;
    else
        cookieValue = propertyId;
    setDefaultPropertyCookie(cookieValue);
}

function removePropertyOnIndexPage(propertyId)
{
    removeProperty(propertyId, 1);
}

function removeProperty(propertyId, isIndexPage)
{
    var i;
    var newCookieValue = '';
    var cookieValue = dojo.cookie(cookiePropertyName);
    var listOfProperty;

    if (cookieValue != null)
    {
        listOfProperty = cookieValue.split(",");
        for (i=0;i<listOfProperty.length;i++)
        {
            if (parseInt(listOfProperty[i]) != parseInt(propertyId))
            {
                newCookieValue += listOfProperty[i] + ",";
            }
        }
        newCookieValue = newCookieValue.substring(0, (newCookieValue.length - 1));
    }
    setSaveOrRemoveLink(propertyId, isIndexPage, 1);
    setDefaultPropertyCookie(newCookieValue);
}

function setSaveOrRemoveLink(propertyId, isIndexPage, isSave)
{
    var saveOrRemove;
    var printContent = '';

    if (isIndexPage == 1)
        saveOrRemove = dojo.byId("saveOrRemoveIndexPage" + propertyId);
    else
        saveOrRemove = dojo.byId("saveOrRemove" + propertyId);
    if (saveOrRemove != null)
    {
        if (isSave == 0)
            printContent = "<a class='removeLink' href='javascript:void(0)' onclick=\"removeProperty('" + propertyId + "', " + isIndexPage + ")\">移除</a>";
        else
            printContent = "<a href='javascript:void(0)' onclick=\"saveProperty('" + propertyId + "');setSaveOrRemoveLink(" + propertyId + ", " + isIndexPage + ", 0);\">儲存</a>";
        saveOrRemove.innerHTML = printContent;
    }
}

function removeAllProperty(isIndexPage)
{
    var i;
    var cookieValue = dojo.cookie(cookiePropertyName);
    var listOfProperty;

//    dojo.cookie(cookiePropertyName, '', {expires: -1});
    if (cookieValue != null)
    {
         listOfProperty = cookieValue.split(",");
        for (i=0;i<listOfProperty.length;i++)
        {
            removeProperty(listOfProperty[i], isIndexPage);
        }
    }
    dojo.cookie(cookiePropertyName, '', {expires: -1});
}

function combineSearchPropertyLinkWithState(baseUrl, searchLink, pageNumber, allQueryString)
{
    var combinedString;
    combinedString = "searchProperty('" + baseUrl +"', '" + searchLink + "', " + pageNumber + ", '" + allQueryString + "');";
    combinedString += "storeState('" + baseUrl +"', '" + searchLink + "', " + pageNumber + ", '" + allQueryString + "')";
    console.debug("combinedString=" + combinedString);
    eval(combinedString);
//    return combinedString;
}

function storeState(baseUrl, searchLink, pageNumber, allQueryString)
{
    var link = "(" + "'" + baseUrl + "','" + searchLink + "'," + pageNumber + ",'" + allQueryString + "')";
    var appState = new ApplicationState(link, link);
    dojo.back.addToHistory(appState);
}

function showSavedProperty(baseUrl)
{
    var linkToGo;
    var cookieValue = dojo.cookie(cookiePropertyName);
    if ((cookieValue != null) && (cookieValue != ''))
    {
        linkToGo = baseUrl + "/display/show-saved-property?propertyIds=" + cookieValue;
        myOpenWin(linkToGo, 1000, 700, "SavedProperty");
    }
    else
    {
        alert("沒有已儲存的樓盤﹗");
    }
}

function deleteProperty(baseUrl, propertyId)
{
    var yesOrNo = confirm("真的要刪除?");
    if (yesOrNo)
    {
        dojo.xhrGet(
            {
// The following URL must match that used to test the server.
                url: baseUrl + "/admin/delete-property?propertyId=" + propertyId, 
                handleAs: 'json',
                timeout: 5000, // Time in milliseconds
// The LOAD function will be called on a successful response.
                load: function(responseData, ioArgs)
                {
//                console.debug(responseData);
//                    alert(responseData);
                    if (responseData == "Done")
                    {
                        location.reload(true);
                    }
                },
                error: function(response, ioArgs)
                {
                    console.debug(response);
                    console.error("HTTP status code: ", ioArgs.xhr.status);
                    return response;
                }
            });
    }
}

function searchProperty(baseUrl, searchLink, pageNumber, allQueryString)
{
    var numberOfPageLink = 10;
    var startPage = 1;
    var printContent = '';

//    console.debug('helloe again');
    displayLoading(true);
    dojo.xhrGet(
        {
// The following URL must match that used to test the server.
            url: baseUrl + searchLink + "?pageNumber=" + pageNumber + "&" + allQueryString,
            handleAs: 'json',
            timeout: 5000, // Time in milliseconds
// The LOAD function will be called on a successful response.
            load: function(responseData, ioArgs)
            {
                console.debug(responseData);
                tbodyTag = dojo.byId('searchContentDiv');
                printContent = "<table width='100%' border='0' cellpadding='0' cellspacing='0'>";
                printContent += "<tbody>";
                printContent += "<tr>";
                printContent += "<td class='searchPageContentTd'>";
                    printContent += "<table width='100%' border='0' cellpadding='0' cellspacing='0'>";
                    printContent += "<tbody>";
                    printContent += "<tr>";
                    printContent += "<td>";
                        printContent += "<table width='100%' border='0' cellpadding='0' cellspacing='4'>";
                        printContent += "<tbody>";
                        printContent += "<tr>";
                        printContent += "<td class='searchInformation' align='left'><a class='removeLink' href='javascript:void(0)' onclick=\"removeAllProperty(0)\">全部移除</a>&nbsp;&nbsp;<a href='javascript:void(0)' onclick=\"showSavedProperty('" + baseUrl + "')\">已存樓盤</a></td>";
                        printContent += "<td class='searchInformation' align='right'>";
                        if (responseData.results.length > 0)
                        {
                            printContent += responseData.results[0].recordNumber + " - " + responseData.results[responseData.results.length - 1].recordNumber;
                        }
                        printContent += "&nbsp;&nbsp;共&nbsp;" + responseData.totalRecord;
                        printContent += "&nbsp;個搜尋結果";
                        printContent += "</td>";
                        printContent += "</tr>";
                        printContent += "<tbody>";
                        printContent += "</table>";
                    printContent += "</td>";
                    printContent += "</tr>";
                    if (responseData.totalRecord == 0)
                    {
                        printContent += "<tr>";
                        printContent += "<td align='center'>";
                        printContent += "找不到相關資料";
                        printContent += "</td>";
                        printContent += "</tr>";
                    }
                    else
                    {
                        printContent += "<tr>";
                        printContent += "<td>";
                        printContent += "<table id='searchContentTableFrame' height='30' width='100%' border='0' cellpadding='0' cellspacing='0'>";
                        printContent += "<tbody>";
                        printContent += "<tr class='searchContentHeading'>";
                        printContent += "<td width='20'>&nbsp;</td>";
                        printContent += "<td width='50' height='10'>實景</td>";
                        printContent += "<td>樓宇名稱</td>";
                        printContent += "<td>街道</td>";
                        printContent += "<td>面積</td>";
                        printContent += "<td>售價(HK$)</td>";
                        printContent += "<td>租金(HK$)</td>";
                        printContent += "<td>包括</td>";
                        printContent += "<td>摘要</td>";
                        printContent += "<td>&nbsp;</td>";
                        if (globolMode == 1)
                            printContent += "<td>編輯</td>";
                        printContent += "</tr>";
                        for (i=0;i<responseData.results.length;i++)
                        {
                            if (i%2 != 0)
                            {
                                rowStyle = "searchEvenRow";
                            }
                            else
                                rowStyle = "searchOddRow";
                            printContent += "<tr class='searchContent " + rowStyle + "'>";
                            printContent += "<td>";
                            printContent += "<font id='linkNumber'>" + responseData.results[i].recordNumber + ".</font>";
                            printContent += "</td>";
                            printContent += "<td><a href=\"javascript:void(0)\" onclick=\"myOpenWin('" + baseUrl + "/display/property?propertyId=" + responseData.results[i].propertyId + "&recordNumber=" + responseData.results[i].recordNumber + "', " + popUpWindowWidth + ", " + popUpWindowHeight + ", 'showProperty" + responseData.results[i].propertyId + "')\">" + responseData.results[i].propertyMainImage + "</a></td>";
                            printContent += "<td>" + responseData.results[i].propertyBuildingName + "</td>";
                            printContent += "<td>" + responseData.results[i].propertyStreet + "</td>";
                            printContent += "<td>" + responseData.results[i].propertySize + "</td>";
                            printContent += "<td>" + responseData.results[i].propertyPriceSell + "</td>";
                            printContent += "<td>" + responseData.results[i].propertyPriceRent + "</td>";
                            printContent += "<td>" + responseData.results[i].propertyInclude + "</td>";
                            printContent += "<td>" + responseData.results[i].propertyDescription + "</td>";
                            if (propertyInTheListAlready(responseData.results[i].propertyId))
                            {
                                printContent += "<td><span id='saveOrRemove" + responseData.results[i].propertyId + "'><a class='removeLink' href='javascript:void(0)' onclick=\"removeProperty('" + responseData.results[i].propertyId + "', 0)\">移除</a></span></td>";
                            }
                            else
                            {
                                printContent += "<td><span id='saveOrRemove" + responseData.results[i].propertyId + "'><a href='javascript:void(0)' onclick=\"saveProperty('" + responseData.results[i].propertyId + "');setSaveOrRemoveLink(" + responseData.results[i].propertyId + ", 0, 0);\">儲存</a></span></td>";
                            }
                            if (globolMode == 1)
                                printContent += "<td><a href='" + modifyLink + "?propertyId=" + responseData.results[i].propertyId + "'>修改</a><br><a href='javascript:void(0)' onclick=\"deleteProperty('" + baseUrl + "', '" + responseData.results[i].propertyId + "')\">刪除</a></td>";
                            printContent += "</tr>";
                        }
                        printContent += "</tbody>";
                        printContent += "</table>";
                        printContent += "</td>";
                        printContent += "</tr>";
                    }
                    printContent += "</tbody>";
                    printContent += "</table>";
                printContent += "</td>";
                printContent += "</tr>";
                printContent += "<tr>";
                printContent += "<td>";
                    printContent += "<table width='100%' border='0' cellpadding='1' cellspacing='1'>";
                    printContent += "<tbody>";
                    printContent += "<tr>";
                    printContent += "<td width='450' align='right'>&nbsp;";
                    if (responseData.totalPage > 1)
                    {
                        halfPageLink = (numberOfPageLink / 2);
                        startPage = responseData.currentPage - halfPageLink;
                        if (responseData.currentPage != 0)
                        {
//                            printContent += "<a href='#' onclick=\"" + combineSearchPropertyLinkWithState(baseUrl, searchLink, 0, allQueryString) + "\">最前</a>&nbsp;&nbsp;";
                            printContent += "<a href='javascript:void(0)' onclick=\"combineSearchPropertyLinkWithState('" + baseUrl + "', '" + searchLink + "', 0, '" + allQueryString + "')\">最前</a>&nbsp;&nbsp;";
                        }
                        if (responseData.hasPreviousPage)
                        {
//                            printContent += "<a href='#' onclick=\"" + combineSearchPropertyLinkWithState(baseUrl, searchLink, (pageNumber - 1), allQueryString) + "\">上一頁</a>";
                            printContent += "<a href='javascript:void(0)' onclick=\"combineSearchPropertyLinkWithState('" + baseUrl + "', '" + searchLink + "', " + (pageNumber - 1) + ", '" + allQueryString + "')\">上一頁</a>";
                            printContent += "&nbsp;";
                        }
                        if (startPage <= 0)
                        {
                            startPage = 1;
                        }
//                        console.debug("currentPage=" + responseData.currentPage + " startPage=" + startPage + " halfPageLink=" + halfPageLink);
                        endPage = numberOfPageLink + startPage;
                        if ((responseData.totalPage - startPage) < numberOfPageLink)
                        {
                            startPage = responseData.totalPage - numberOfPageLink + 1;
                            if (startPage <= 0)
                            {
                                startPage = 1;
                            }
                        }
                        printContent += "</td>";
                        printContent += "<td width='150' align='center'>";
//                        console.debug("(responseData.totalPage - startPage)=" + (responseData.totalPage - startPage) + "startPage=" + startPage);
                        for (k=startPage;k<endPage;k++)
                        {
                            if (k <= responseData.totalPage)
                            {
                                if ((k - 1) == responseData.currentPage)
                                {
                                    linkStyleText = "<font class='searchCurrentLink'>" + k + "</font>";
                                    printContent += linkStyleText;
                                }
                                else
                                {
                                    linkStyleText = k;
//                                    printContent += "<a href='#' onclick=\"" + combineSearchPropertyLinkWithState(baseUrl, searchLink, (k - 1), allQueryString) + "\">" + linkStyleText + "</a>";
                                    printContent += "<a href='javascript:void(0)' onclick=\"combineSearchPropertyLinkWithState('" + baseUrl + "', '" + searchLink + "', " + (k - 1) + ", '" + allQueryString + "')\">" + linkStyleText + "</a>";
                                }
                                if (k < 10)
                                    printContent += "&nbsp;&nbsp;";
                                else
                                    printContent += "&nbsp;";
                            }
                            else
                                break;
                        }
                        printContent += "</td>";
                        printContent += "<td align='left'>";
                        if (responseData.hasNextPage)
                        {
//                            printContent += "<a href='#' onclick=\"" + combineSearchPropertyLinkWithState(baseUrl, searchLink, (pageNumber + 1), allQueryString) + "\">下一頁</a>";
                            printContent += "<a href='javascript:void(0)' onclick=\"combineSearchPropertyLinkWithState('" + baseUrl + "', '" + searchLink + "', " + (pageNumber + 1) + ", '" + allQueryString + "')\">下一頁</a>";
                        }
                        if (responseData.currentPage != (responseData.totalPage - 1))
                        {
//                            printContent += "&nbsp;&nbsp;<a href='#' onclick=\"" + combineSearchPropertyLinkWithState(baseUrl, searchLink, (responseData.totalPage - 1), allQueryString) + "\">最後</a>";
                            printContent += "&nbsp;&nbsp;<a href='javascript:void(0)' onclick=\"combineSearchPropertyLinkWithState('" + baseUrl + "', '" + searchLink + "', " + (responseData.totalPage - 1) + ", '" + allQueryString + "')\">最後</a>";
                        }
                    }
                    printContent += "</td>";
                    printContent += "</tr>";
                    printContent += "</tbody>";
                    printContent += "</table>";
                printContent += "</td>";
                printContent += "</tr>";
                printContent += "</tbody>";
                printContent += "</table>";
                tbodyTag.innerHTML = printContent;
                displayLoading(false);
                return responseData;
            },
// The ERROR function will be called in an error case.
            error: function(response, ioArgs)
            {
                console.debug(response);
//                console.debug(ioArgs);
                console.error("HTTP status code: ", ioArgs.xhr.status);
                displayLoading(false);
                return response;
            }
        }
    );
}

