
var downloadpath = "/Service/Download";
var downloadhost = "http://"+document.domain.replace("www","download");
var imagepath = "../../Content/";
var serverpath = "/Service";
var devpath = "http://" + document.domain.replace("www", "developer");
var userpicpath = "../../Content/temp/userpic";
var homeurl = document.domain;
//var pagename = jQuery.url.param("pageid");
var pagename = $("#pageid").attr("innerHTML");
//alert(pagename);
var areacode = "en"; 
var area = 1;
var nav="free";
var confirm = false;


function init() {

    MM_reloadPage(true);

    // check area for language
    checkPage();
    checkArea(areacode);
    checkSession();
	
	if (typeof (HTTP_LOGIN_SOURCE_URL) == "boolean" && HTTP_LOGIN_SOURCE_URL == true) {
    	openEULATools();
    }

}

function browsercheck() {
    if ($.browser.msie) {
        if ($.browser.version == "6.0" || $.browser.version == "7.0") alert(" In order to provide a better experience for our users, Internet Explorer 6 and 7 are no longer supported. Please use a more recent browser, such as Internet Explorer 8, Firefox, Safari, or Chrome to best experience Insyde Market.");
    }
}

function checkPage() {
    //alert($("#pageid").attr("innerHTML"));
    pagename = $("#pageid").attr("innerHTML");
    var pagelist = ["ENBLG", "ENNWS", "ENLGOT", "ENPLYMB", "ENSUPTLS", "ENPLYPV", "ENABU", "ENMBRENDMC", "ENMBRENDPH", "ENSUPCNT", "ENSUPFAQ", "ENMBRENDAD", "ISYMRKEN", "ENDWN", "ENDWNDTL", "ENMBRENDPWS", "ENJONS3E", "ENJONS5", "ENJONS5E", "ENJONSUSE", "ENJONREE", "ENMBRENDPF", "ENMBRENDPW", "ENMBRENDMIL", "ENPMSRC", "DVCTPC", "DVDMCA", "ENLGIN", "ENEVENT"];

    if (jQuery.inArray(pagename, pagelist) == -1) {
        $("body").attr("innerHTML", "");
        alert("This funcion is not currently opened, if you have any problem, please contact the system administrator, thank you!(" + pagename + ")");
        window.history.back();
    }
}

function checkArea(areacode) {
    $.ajax({
        url: serverpath + '/checkArea',
        type: "POST",
        data: ({
            action: "checkArea",
            areacode: areacode
        }),
        async: false,
        datatype: "JSON",
        success: function (data) {
            //alert(data.result);
            area = data.result;
        }
    });
}

// check area for user interface language

function checkSession() {
    //alert('checkSession');
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            var denypage = ["ENMBRENDPF", "ENMBRENDMIL", "ENMBRENDAD", "ENMBRENDPH", "ENMBRENDMC", "ENMBRENDPW", "ENSUPTLS"];

            if (data == "guest" && jQuery.inArray(pagename, denypage) != -1) {
                $("body").attr("innerHTML", "");
                openLoginDialog();
                return;
            }

            if (data != "guest") {
                $("#home_mac").css("display", "inline");
            }

            $.ajax({
                url: serverpath + '/checkSession',
                type: "POST",
                data: ({
                    action: "checkSession",
                    username: data
                }),
                datatype: "JSON",
                success: function () {
                    $.ajax({
                        url: "/Handle/checkSession",
                        type: "POST",
                        data: ({
                            act: "checkSession"
                        }),
                        success: function (data) {
                            $("#logDiv").attr("innerHTML", data);
                            //alert(pagename);
                            templateGen(pagename);
                        }
                    });
                }
            });
        }
    });
}

// load template required pages

function templateGen(pagename) {
//    var template = jQuery.url.attr("file").split('.')[0].toLowerCase();
    var template = pagename;
    switch (template) {
        // 1.Home        
    case "ISYMRKEN":
    case "ENSUPCNT":
    case "ENLGIN":
        getResource(pagename, area);
        break;

        // 2.Application_List        
        // 3.Application_Detail        
    case "ENDWN":
    case "ENDWNDTL":
    case "ENMBRENDAD":
        $.get("../../Content/form/" + pagename + ".html", function (data) {
            $("#mainleft").attr("innerHTML", data);
            getResource(pagename, area);
        });
        break;

        // 5.Forget Pwd        
        // 6.SignUp Form        
        // 7.SignUp Check        
        // *.SignUp Check (change email)        
        // 8.SignUp Finish        
        // 9.SignUp Verify        
    case "ENMBRENDPWS":
    case "ENJONS3E":
    case "ENJONS5":
    case "ENJONREE":
    case "ENJONSUSE":
    case "ENJONS3E":
        if ((pagename == "ENJONS3E") || (pagename == "ENJONREE") || (pagename == "ENMBRENDPWS"))
		{
			//$.get("../../Content/form/" + pagename + ".php", function (data) {
			//	$("#mainContent").attr("innerHTML", data);
				getResource(pagename, area);
		//	});
		}
		else
		{
			$.get("../../Content/form/" + pagename + ".html", function (data) {
				$("#mainContent").attr("innerHTML", data);
				getResource(pagename, area);
			});
		}
        break;

        // 10.MyProfile        
        // 11.ChangePw        
        // 12.My Installation Lib        
        // 13.MemAppDetail        
        // 14.FAQ        
        // 15.Contact Us        
        // 16.MyPurchase History     
    case "ENMBRENDPF":
    case "ENMBRENDMIL":     
  //  case "ENSUPCNT":
    case "ENSUPFAQ":
    case "ENABU":
    case "ENMBRENDPH":
    case "ENSUPTLS":
        //alert("test28");
        $.get("../../Content/form/" + pagename + ".html", function (data) {
            $("#contentDiv").attr("innerHTML", data);
            getResource(pagename, area);
        });
        break;

        // 17.Member Account Center        
        // 18.About INSYDE MARKET        
        // 19.Privacy Policy        
        // 20.Site Term        
        // 21.Logout        
        // 22.News        
        // 23.Blog  
    case "ENMBRENDMC":          
    case "ENABU":
    case "ENLGOT":
    case "ENPMSRC":
    case "ENPLYPV":
    case "ENPLYMB":
    case "ENLGOT":
		if(pagename == "ENMBRENDMC")
		{
		//	$.get("../../Content/form/" + pagename + ".php", function (data) {
		//		$("#contentDiv").attr("innerHTML", data);
				getResource(pagename, area);
		//	});
		}
		else
		{
			$.get("../../Content/form/" + pagename + ".html", function (data) {
				$("#contentDiv").attr("innerHTML", data);
				getResource(pagename, area);
			});
		}
        break;
    //2011/10/21 AppStar Event Change  
    case "ENEVENT":
        getResource(pagename, area);
        break;
    }
}

function getResource(pagename, area) {

    $.ajax({
        url: serverpath + '/getResource',
        type: "POST",
        data: ({
            action: "getResource",
            pagename: pagename,
            area: area
        }),
        datatype: "JSON",
        success: function (data) {
            //alert(data.status);
            if (data.status == "success") {
                var jsonobj = data.result;
                //alert(jsonobj);
                // apply common resources
                for (key in jsonobj) {
                    // alert(jsonobj[key].Resource_id);
                    switch (jsonobj[key].Resource_id) {
                        case "favImg":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "addHref":
                            $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                            break;
                        case "acTxt":
                            $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                            break;
                        case "logHref":
                            $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                            break;
                        case "signImg":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "logoImg":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "appImg_Load":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "newsImg_Load":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "blogImg_Load":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "supportImg_Load":
                            $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                            break;
                        case "appImg_Over":
                            $("#" + jsonobj[key].Resource_id).attr("onMouseOver", "MM_swapImage('" + $("#" + jsonobj[key].Resource_id + ' img').attr('name') + "','','" + imagepath + jsonobj[key].Link + "',0)");
                            break;
                        case "newsImg_Over":
                            $("#" + jsonobj[key].Resource_id).attr("onMouseOver", "MM_swapImage('" + $("#" + jsonobj[key].Resource_id + ' img').attr('name') + "','','" + imagepath + jsonobj[key].Link + "',0)");
                            break;
                        case "blogImg_Over":
                            $("#" + jsonobj[key].Resource_id).attr("onMouseOver", "MM_swapImage('" + $("#" + jsonobj[key].Resource_id + ' img').attr('name') + "','','" + imagepath + jsonobj[key].Link + "',0)");
                            break;
                        case "supportImg_Over":
                            $("#" + jsonobj[key].Resource_id).attr("onMouseOver", "MM_swapImage('" + $("#" + jsonobj[key].Resource_id + ' img').attr('name') + "','','" + imagepath + jsonobj[key].Link + "',0)");
                            break;
                        case "blogurl":
                            //$("#blogImg_Over").attr("href", jsonobj[key].Link);
                            $("#blogImg_Over").attr("href", "javascript:blog('" + jsonobj[key].Link + "')");
                            break;
                        case "newsurl":
                            //$("#newsImg_Over").attr("href", jsonobj[key].Link);
                            $("#newsImg_Over").attr("href", "javascript:news('" + jsonobj[key].Link + "')");
                            $("#home_news").attr("href", "javascript:news('" + jsonobj[key].Link + "')");
                            break;
                        case "pathAreaSet":
                            $("#pathAreaSet").append(jsonobj[key].Link);
                            break;
                        case "category":
                            $("#category").append(jsonobj[key].Link);
                            break;
                        case "footerLinks":
                            var links = jsonobj[key].Link.split(',');
                            var footerHtml = "<a href=\"http://" + homeurl + "/Support/Faq\" class=\"footer_link\">" + links[0] + "</a> | ";
                            footerHtml += "<a href=\"http://" + homeurl + "/Home/AboutUs\" class=\"footer_link\">" + links[1] + "</a> | ";
                            footerHtml += "<a href=\"http://" + homeurl + "/Support/ContactUs\" class=\"footer_link\">" + links[2] + "</a>";
                            $("#" + jsonobj[key].Resource_id).html(footerHtml);
                            break;
                        case "footerInfo":
                            var footerinfo = jsonobj[key].Link.replace('Site Terms of Service', '<a class="copyright_link" href="http://'+homeurl+'/Home/TermsofService">Site Terms of Service</a>');
                            footerinfo = footerinfo.replace('Privacy Policy', '<a class="copyright_link" href="http://' + homeurl + '/Home/PrivacyPolicy">Privacy Policy</a>');
                            footerinfo = footerinfo.replace('Google Permissions', '<a class="copyright_link" href="http://www.google.com/permissions/index.html" target="_blank">Google Permissions</a>');

                            $("#footerInfo").html('<span class="copyright">' + footerinfo + '</span>');
                            break;
                    }
                }
                placingResources(pagename, jsonobj);

                // list resources
                /*
                * var string = ""; $('body').append("Get Resource<br>status :
                * success load <br>"); for (key in jsonobj) string =
                * string + ("position:" + jsonobj[key].Resource_id) +
                * "====" + "link:" + (jsonobj[key].Link) + "<br>";
                * $('body').append(string);
                */

            }
        }
    });

}

function placingResources(pagename, jsonobj) {
   // alert("placingResources="+pagename);
    switch (pagename) {
        // 1.Home        
    case "ISYMRKEN":
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "freeImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "paidImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "fmrImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "fmpImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "fhrImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "pmrImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "pmpImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "phrImg_Load":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "rightMenuTitle":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "bigBanner":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "bigBannerHref":
                $("#bigBannerHref").attr("href", devpath);
                break;
            }
        }
        var fmrStr = $("#fmrImg_Load").attr("src");
        var pmrStr = $("#pmrImg_Load").attr("src");
        var fbtStr = $("#freeImg_Load").attr("src");
        $("#fmrImg_Load").attr("src", fmrStr.substring(0, fmrStr.length - 4) + "R" + fmrStr.substring(fmrStr.length - 4, fmrStr.length));
        $("#pmrImg_Load").attr("src", pmrStr.substring(0, pmrStr.length - 4) + "R" + pmrStr.substring(pmrStr.length - 4, pmrStr.length));
        $("#freeImg_Load").attr("src", fbtStr.substring(0, fbtStr.length - 4) + "R" + fbtStr.substring(fbtStr.length - 4, fbtStr.length));
        $("#PaidApp").css("display", "none");

        // get api
        getNewsList(area);
        getSpotLight(area);
        getCategory(area);
        getMostRecentApps(pagename, area, "FREE", 10, 1);
        getMostPopularApps(pagename, area, "FREE", 10, 1);
        getMostRatedApps(pagename, area, "FREE", 10, 1);
        getMostRecentApps(pagename, area, "PAID", 10, 1);
        getMostPopularApps(pagename, area, "PAID", 10, 1);
        getMostRatedApps(pagename, area, "PAID", 10, 1);
        getAdvertisement();
        getRelatedLink();
        browsercheck();
        break;

        // 2.Application_List
    case "ENDWN":
        document.title = "Applications | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
                case "freeImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "paidImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "fmrImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "fmpImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "fhrImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "pmrImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "pmpImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "phrImg_Load":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "rightMenuTitle":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
            }
        }

        var src1, src2, src3, src4, src5, src6;
        switch (jQuery.url.param("nav")) {
            case "1":
                src1 = "fmrImg_Load";
                src2 = "pmrImg_Load";
                src3 = "freeImg_Load";
                src4 = "PaidApp";
                src5 = "FreeApp";
                src6 = "topFreeMR";
                break;
            case "2":
                src1 = "fmpImg_Load";
                src2 = "pmrImg_Load";
                src3 = "freeImg_Load";
                src4 = "PaidApp";
                src5 = "FreeApp";
                src6 = "topFreeMP";
                break;
            case "3":
                src1 = "fhrImg_Load";
                src2 = "pmrImg_Load";
                src3 = "freeImg_Load";
                src4 = "PaidApp";
                src5 = "FreeApp";
                src6 = "topFreeHR";
                break;
            case "4":
                src1 = "pmrImg_Load";
                src2 = "fmrImg_Load";
                src3 = "paidImg_Load";
                src4 = "FreeApp";
                nav = "paid";
                src5 = "PaidApp";
                src6 = "topPaidMR";
                break;
            case "5":
                src1 = "pmpImg_Load";
                src2 = "fmrImg_Load";
                src3 = "paidImg_Load";
                src4 = "FreeApp";
                nav = "paid";
                src5 = "PaidApp";
                src6 = "topPaidMP";
                break;
            case "6":
                src1 = "phrImg_Load";
                src2 = "fmrImg_Load";
                src3 = "paidImg_Load";
                src4 = "FreeApp";
                nav = "paid";
                src5 = "PaidApp";
                src6 = "topPaidHR";
                break;
            default:
                src1 = "fmrImg_Load";
                src2 = "pmrImg_Load";
                src3 = "freeImg_Load";
                src4 = "PaidApp";
                src5 = "FreeApp";
                src6 = "topFreeMR";
                break;

        }
        var fmrStr = $("#" + src1).attr("src");
        var pmrStr = $("#" + src2).attr("src");
        var fbtStr = $("#" + src3).attr("src");
        $("#" + src1).attr("src", fmrStr.substring(0, fmrStr.length - 4) + "R" + fmrStr.substring(fmrStr.length - 4, fmrStr.length));
        $("#" + src2).attr("src", pmrStr.substring(0, pmrStr.length - 4) + "R" + pmrStr.substring(pmrStr.length - 4, pmrStr.length));
        $("#" + src3).attr("src", fbtStr.substring(0, fbtStr.length - 4) + "R" + fbtStr.substring(fbtStr.length - 4, fbtStr.length));
        $("#" + src4).css("display", "none");
        $("#" + src5 + " div").css("display", "none");
        $("#" + src6).css("display", "table");
        getCategory(area);

        // get by category
        if (jQuery.url.param("cat") != undefined) {
            //alert(jQuery.url.param("cat"));
            placeAppByCat(jQuery.url.param("cat"));
        } else if (jQuery.url.param("keyword") != undefined) {
            $("#query_kw").val(jQuery.url.param("keyword"));
            queryApp(jQuery.url.param("keyword"));
        } else {
            getMostRecentApps(pagename, area, "FREE", 10, 1);
            getMostPopularApps(pagename, area, "FREE", 10, 1);
            getMostRatedApps(pagename, area, "FREE", 10, 1);
            getMostRecentApps(pagename, area, "PAID", 10, 1);
            getMostPopularApps(pagename, area, "PAID", 10, 1);
            getMostRatedApps(pagename, area, "PAID", 10, 1);
        }
        ISYMRKEN();
        break;

        // 3.Application_Detail        
    case "ENDWNDTL":
        document.title = "Download Details | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "rightMenuTitle":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "downloadBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "priceTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "catTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "desTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }

        // get Api
        getCategory(area);
        getAppsDetail(area);
        ENDWNDTL();
        break;

        // 5.Forget Pwd        
    case "ENMBRENDPWS":
        document.title = "Forget your password? | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "mainBanner":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "submitBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "titleTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "emailTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "codeTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "fillTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "diffTxt":
                $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                break;
            }
        }
        ENMBRENDPWS();
        $('#captchaImg').attr('src', '/Handel/showcaptcha?' + Math.random());
        break;

        // 6.SignUp Form
    case "ENJONS3E":
        document.title = "SignUp Member | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
                case "mainBanner":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "titleImg_step1":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "toDevBtn":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "submitBtn":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "requiredTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "emailTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "cfEmailTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "pwdTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "pwdLimitTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "cfPwdTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "level2Txt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "fnameTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "lnameTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "chkAviTxt":
                    $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                    break;
                case "limitTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "companyTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "phoneNoTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "phoneExTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "addrTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "postcodeTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "countryTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "codeTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "fillTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "diffTxt":
                    $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                    break;
                //case "SitetermContentSign": 
                //$("#" + jsonobj[key].Resource_id).attr("src", jsonobj[key].Link); 
                //   $("#" + jsonobj[key].Resource_id).attr("src", "http://www2.copycat.tw/Content/sign_siteterms.html"); 
                    break;
                case "agreeTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
            }
        }

        $.ajax({
            url: serverpath + '/getCountry',
            type: "POST",
            data: ({
                action: "getCountry"
            }),
            datatype: "JSON",
            success: function (data) {
                var option = "";
                $.each(data.data, function (key, value) {
                    option+="<option value=\"" + value.Id + "\" item=\"" + value.Id + "\">" + value.Name + "</option>";
                });
                $("#sign_country").html($("#sign_country").html()+option);
            }
        });

        //        $.getJSON("../../Content/country/en.txt", function (data) {
        //            $.each(data, function (key, value) {
        //                $("#sign_country").append("<option value=\"" + key + "\" item=\"" + value + "\">" + key + "</option>");
        //            });
        //        });

        if ($("#signup_provider").html() != "") {
            var provider = eval('(' + $("#signup_provider").html() + ')');
            if (provider.firstname != null) {
                $("#sign_fname").val(provider.firstname);
            }
            if (provider.lastname != null) {
                $("#sign_lname").val(provider.lastname);
            }
            if (provider.email != null) {
                $("#sign_email").val(provider.email);
                $("#sign_email").attr("readonly", true);
                $("#sign_cfEmail").val(provider.email);
                $("#sign_cfEmail").attr("readonly", true);
            }
        }

        getRegistrationProfile();
        ENJONS3E();

        break;

        // 7.SignUp Check        
    case "ENJONS5":
        document.title = "Check your email | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "mainBanner":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "titleImg_step2":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "contentImg_step4":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "notReceiveHref":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }
        break;

    case "ENJONS5E":
        document.title = "Check your email | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "mainBanner":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "titleImg_step2":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "checkEmailTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link.split('.')[0] + ".<br/>" + jsonobj[key].Link.split('.')[1] + ".");
                break;
            }
        }
        break;

        // 8.SignUp Finish        
    case "ENJONSUSE":
        document.title = "Congratulations | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "mainBanner":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "titleImg_step3":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "contentImg_end":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            }
        }

        checkUserVerification();
        break;

        // 9.SignUp Verify        
    case "ENJONREE":
        document.title = "Not received verification mail | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "mainBanner":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "emailTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "resendBtn":
                $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                break;
            }
        }
        ENJONREE();
       // $('#captchaImg').attr('src', '/Handle/showcaptcha?' + Math.random());
        break;

        // 10.MyProfile
    case "ENMBRENDPF":
        document.title = "Member Profile | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
                case "submitBtn":
                    $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                    break;
                case "requiredTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "pictureTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "picLtdTxt":
                    $("#" + jsonobj[key].Resource_id + "0").attr("innerHTML", jsonobj[key].Link.split(',')[0]);
                    $("#" + jsonobj[key].Resource_id + "1").attr("innerHTML", jsonobj[key].Link.split(',')[1]);
                    break;
                case "emailTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "pwdTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "chgPwdBtn":
                    $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                    break;
                case "level2Txt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "fnameTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "lnameTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "phoneNoTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "phoneExTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "addrTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "postcodeTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "countryTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "timeTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "langTxt":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "notify1":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "notify2":
                    $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                    break;
                case "rightLinks":
                    $("#" + jsonobj[key].Resource_id).append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                    break;
                case "rightTitleAC":
                    $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                    break;
            }
        }

        $.ajax({
            url: serverpath + '/getCountry',
            type: "POST",
            data: ({
                action: "getCountry"
            }),
            datatype: "JSON",
            success: function (data) {
                var option = "";
                $.each(data.data, function (key, value) {
                    // $("#profile_country").append("<option value=\"" + value.Id + "\" item=\"" + value.Id + "\">" + value.Name + "</option>");
                    option += "<option value=\"" + value.Id + "\" item=\"" + value.Id + "\">" + value.Name + "</option>";
                });
                $("#profile_country").html($("#profile_country").html() + option);
                getMemberProfile();
            }
        });

        $.getJSON("../../Content/language/en.txt", function (data) {
            $.each(data, function (key, value) {
                $("#profile_lang").append("<option value=\"" + key + "\">" + value + "</option>");
            });
        });


        ENMBRENDPF();
        break;

        // 11.ChangePw        
    case "ENMBRENDPW":
        document.title = "Change password | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "submitBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "newPwdTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "cfNewPwdTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "pwdLimitTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "rightLinks":
                $("#" + jsonobj[key].Resource_id).append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "rightTitleAC":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }
        ENMBRENDPW();
        break;

        // 12MEMBER LIBRARY        
    case "ENMBRENDMIL":
        document.title = "Installation library | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "rightLinks":
                $("#" + jsonobj[key].Resource_id).append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "catTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "keywordTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "dwdateTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "rightTitleAC":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }

        getCategory(area);
        ENMBRENDMIL();
        break;

        // 13.MemAppDetail        
    case "ENMBRENDAD":
        document.title = "Download Details | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "rightLinks":
                $("#" + jsonobj[key].Resource_id).append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "uploadedTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "downloadedTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "priceTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "rateTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "rightTitleAC":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }

        getMemberAppDetail();
        ENMBRENDAD();
        break;

        // 14.FAQ        
    case "ENSUPFAQ":
        document.title = "FAQ | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "rightLinksSUP":
                $("#rightLinks").append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "faqDes":
                $("#faqDes").attr("innerHTML", jsonobj[key].Link);
                break;
            case "rightTitle":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }
        var now = new Date();
        getSupportFiles(getTimestamp(now), area);
        break;

        // 15.Contact Us        
    case "ENSUPCNT":
        document.title = "Contact Us | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "contactTitle":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "requiredTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "nameTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "emailTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "subjectTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "catTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "catOption":
                var str = jsonobj[key].Link.split(',');
                for (s in str)
                $("#" + jsonobj[key].Resource_id).append("<option value=\"" + (parseInt(str[s].split(':')[0]) + 1) + "\">" + str[s].split(':')[1] + "</option>");
                break;
            case "mstTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "codeTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "fillTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "diffTxt":
                $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                break;
            case "submitBtn":
                $("#" + jsonobj[key].Resource_id).attr("value", jsonobj[key].Link);
                break;
            case "rightLinksSUP":
                $("#rightLinks").append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "rightTitle":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }
        ENSUPCNT();
        $('#captchaImg').attr('src', '/Handle/showcaptcha?' + Math.random());
        break;

    case "ENSUPTLS":
        document.title = "Tools | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "rightLinksSUP":
                $("#rightLinks").append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "faqDes":
                $("#faqDes").attr("innerHTML", jsonobj[key].Link);
                break;
            case "rightTitle":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            case "utilDescTxt":
                $("#utilDescTxt").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }
        getTools();
        break;

        // 16.Member Account Center        
    case "ENMBRENDMC":
        //document.title = "Member Account Center | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "myProfBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "myInstallBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "myHistoryBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "backInsydeBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "switchDevBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            case "resDevBtn":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            }
        }

				if(jQuery.url.param("s")!==undefined){
				$.ajax({
				    url: "/Handle/iniSession",
            type: "POST",
            async: false,
            data: ({
                act: "iniSession"
            }),
            success: function (data) {
            	if(data!=decodeURIComponent(jQuery.url.param("s"))){
            		alert("You are currently logged into another account with Insyde Market. Please logout of that account first before proceeding!");
            	}else{
            	
            	}
            }
        });
				}
        $.ajax({
            url: "/Handle/iniSession",
            type: "POST",
            data: ({
                act: "iniSession"
            }),
            success: function (data) {
                $.ajax({
                    url: serverpath+'/getUserProfileByUserName',
                    type: "POST",
                    data: ({
                        action: "getUserProfileByUserName",
                        username: data
                    }),
                    datatype: "JSON",
                    success: function (data) {
                        if (data.status == "success") {
                            var jsonobj = data.result;

                            if (jsonobj[0].mdegree == 0) {
                                alert("You are not a member, please register as a member!");
                                window.location = "/Member/SignUp?email=" + encodeURIComponent(jsonobj[0].user_name);
                            }

                            if (jsonobj[0].ddegree != null && jsonobj[0].ddegree != 0) $("#switchDevBtn").css("display", "inline");
                            else {
                                $("#resDevBtn").parent().attr("href", $("#resDevBtn").parent().attr("href") + "?email=" + encodeURIComponent(jsonobj[0].user_name));
                                $("#resDevBtn").css("display", "inline");
                            }
                            
                            $("#switchDevBtn").parent().attr("href", $("#switchDevBtn").parent().attr("href") + "?email=" + encodeURIComponent(jsonobj[0].user_name));
                        }
                    }
                });
            }
        });
        break;

        // 17.About INSYDE MARKET        
    case "ENABU":
        document.title = "About Insyde Market | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "AboutDiv":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "AboutImg":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            }
        }
        break;

        // 18.Privacy Policy        
    case "ENPLYPV":
        document.title = "Privacy Policy | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "PrivacyContentDiv":
                $.get("../../"+jsonobj[key].Link, function (data) {
                    $("#PrivacyContentDiv").attr("innerHTML", data);
                });
                break;
            }
        }
        break;

        // 19.Site Term        
    case "ENPLYMB":
        document.title = "Site terms of service | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "SitetermContentDiv":
                $.get("../../"+jsonobj[key].Link, function (data) {
                    $("#SitetermContentDiv").attr("innerHTML", data);
                });
                break;
            }
        }
        break;

        // 20.My Purchase History        
    case "ENMBRENDPH":
        document.title = "Purchase History | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "rightLinks":
                $("#" + jsonobj[key].Resource_id).append(
                parseRightLinks(jsonobj[key].Link.split(',')));
                break;
            case "catTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "keywordTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "buyTxt":
                $("#" + jsonobj[key].Resource_id).attr("innerHTML", jsonobj[key].Link);
                break;
            case "rightTitleAC":
                $("#rightTitle").attr("innerHTML", jsonobj[key].Link);
                break;
            }
        }

        getCategory(area);
        ENMBRENDPH();
        break;

        // 21.Member Logout        
    case "ENLGOT":
        document.title = "Logout | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "logoutImg":
                $("#" + jsonobj[key].Resource_id).attr("src", imagepath + jsonobj[key].Link);
                break;
            }
        }
        break;
    case "ENLGIN":
        document.title = "Login | " + document.title;
        $("#pathAreaSet").html('<a href="/">Home</a> > Login');
        $("#category").html('Login');
        $("#addHref").html('Add to Favorites');
        break;
        // 22.News        
    case "ENNWS":
        break;

        // 23.Blog        
    case "ENBLG":
        break;

        // 24.Payment source        
    case "ENPMSRC":
        document.title = "Payment source | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "paymentContentDiv":
                $.get("../../"+jsonobj[key].Link, function (data) {
                    $("#paymentContentDiv").attr("innerHTML", data);
                });
                break;
            }
        }
        break;

        // Content Policy        
    case "DVCTPC":
        document.title = "Content Policy | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "contentPolicyContentDiv":
                $.get(jsonobj[key].Link, function (data) {
                    $("#contentPolicyContentDiv").attr("innerHTML", data);
                });
                break;
            }
        }
        break;

        // DMCA Dispute Policy        
    case "DVDMCA":
        document.title = "DMCA Dispute Policy | " + document.title;
        for (key in jsonobj) {
            switch (jsonobj[key].Resource_id) {
            case "dmcaContentDiv":
                $.get(jsonobj[key].Link, function (data) {
                    $("#dmcaContentDiv").attr("innerHTML", data);
                });
                break;
            }
        }
        break;
    //2011/10/21 AppStar Event Change  
    case "ENEVENT":
        break;
    }

}

function parseRightLinks(rightLinks) {
    var innerHtml = "";
    for (key in rightLinks) {
        innerHtml += "<tr><td>";
        switch (rightLinks[key]) {
        case "Account Center":
            innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"http://"+homeurl+"/Member/Index\">" + rightLinks[key] + "</a>";
            break;
        case "My Profile":
            innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"https://" + homeurl + "/Member/MyProfile\">" + rightLinks[key] + "</a>";
            break;
        case "My Apps","Installed Apps":
            innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"http://" + homeurl + "/Member/Installation\">" + rightLinks[key] + "</a>";
            break;
        case "My Purchase","Purchase Record":
            innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"http://" + homeurl + "/Member/PurchaseHistory\">" + rightLinks[key] + "</a>";
            break;
        case "FAQ":
            innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"http://"+homeurl+"/Support/Faq/\">" + rightLinks[key] + "</a>";
            break;
        case "Contact Us":
            innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"http://" + homeurl + "/Support/ContactUs\">" + rightLinks[key] + "</a>";

            $.ajax({
                url: "/Handle/iniSession",
                type: "POST",
                data: ({
                    act: "iniSession"
                }),
                success: function (data) {
                    if (data != "guest") innerHtml += "<a class=\"mainright_text\" target=\"_parent\" href=\"http://" + homeurl + "/Support/Utilities\">Utilities</a>";
                },
                async: false
            });

            break;
        }
        innerHtml += "</td></tr>";
    }
    return innerHtml;
}

function getNewsList(area) {
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var secs = currentTime.getSeconds();

    var y = currentTime.getFullYear();
    var m = currentTime.getMonth() + 1;
    var d = currentTime.getDate();

    if (m < 10) m = "0" + m;
    if (d < 10) d = "0" + d;
    var time_stamp = y + "-" + m + "-" + d + " " + hours + ":" + minutes + ":" + secs;

    $.ajax({
        url: serverpath+'/getNewsList',
        type: "POST",
        data: ({
            action: "getNewsList",
            time_stamp: time_stamp,
            area: area
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = (data.result);

                // apply NewsList
                var innerHtml = "";
                for (key in jsonobj)
                innerHtml += "<li><a class=\"newsdetail\" href=\"javascript:news('" + jsonobj[key].url + "')\">" + jsonobj[key].title + "</a></li>";
                $("#slidetexts").append(innerHtml);

                var headHtml = "<script type='text/javascript'>";
                headHtml += "slideLine('slidetexts', 5500, 32, 20);";
                headHtml += "</script>";
                $('head').append(headHtml);
            }
        }
    });
}

function getSpotLight(area) {
    $.ajax({
        url: serverpath+'/getSpotLight',
        type: "POST",
        data: ({
            action: "getSpotLight",
            area: area
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                // data =
                var jsonobj = data.result;

                // apply SpotLight
                var innerHtml = "<table width=\"100%\"><tr><td rowspan=\"2\" valign=\"top\" style=\"background-image:url('" + jsonobj.icon + "?" + guid() + "'); background-repeat: no-repeat; background-position: 20px 50%;\"><a href=\"/Application/Detail/" + jsonobj.id + "\">";
                innerHtml += "<img src=\"Content/images/spotlightapp_bg.png\" alt=\"\" class=\"image49\" border=\"0\" width=\"90\" height=\"90\" /></a></td>";
                innerHtml += "<td><a style=\"overflow:hidden;\" href=\"/Application/Detail/" + jsonobj.id + "\" class=\"spotlight\">" + jsonobj.name + "</a></td></tr>";
                innerHtml += "<tr><td><p class=\"spotlight_text\">" + jsonobj.description + "</p></td></tr></table>";
                $("#staffPick").append(innerHtml);
            }
        }
    });
}

function getCategory(area) {
    $.ajax({
        url: serverpath+'/getAppCategory',
        type: "POST",
        data: ({
            action: "getAppCategory",
            area: area
        }),
        datatype: "JSON",
        success: function (data) {

            if (data.status == "success") {
                var jsonobj = data.result;

                if (pagename == "ENMBRENDMIL") {
                    for (key in jsonobj)
                    $("#catOption").append("<option value=\"" + jsonobj[key].ID + "\">" + jsonobj[key].Name + "</option>");
                    getMyInstallations();
                } else if (pagename == "ENMBRENDPH") {
                    for (key in jsonobj)
                    $("#catOption").append("<option value=\"" + jsonobj[key].ID + "\">" + jsonobj[key].Name + "</option>");
                    getPurchaseHistory();
                } else {
                    var innerHtml = "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"mainright\">";
                    for (key in jsonobj) {
                        if (pagename == "ENDWN") {
                            innerHtml += "<tr><td><a id=\"cat" + jsonobj[key].ID + "\" class=\"mainright_text\" target=\"_parent\" href=\"javascript:placeAppByCat(" + jsonobj[key].ID + ")\">" + jsonobj[key].Name + "</a></td></tr>";
                        } else innerHtml += "<tr><td><a id=\"cat" + jsonobj[key].ID + "\" class=\"mainright_text\" target=\"_parent\" href=\"/Application/List?cat=" + jsonobj[key].ID + "\">" + jsonobj[key].Name + "</a></td></tr>";
                    }
                    innerHtml += "</table>";
                    $("#rightMenuContent").append(innerHtml);

                    if (jQuery.url.param("cat") != undefined) $("#cat" + jQuery.url.param("cat")).addClass("mainright_text_select");
                }
            }
        }
    });
}

function getApplicationByCategory(cat, type, area, price, div, number_per_page, pages, bool) {
    $.ajax({
        url: serverpath+'/getApplicationByCategory',
        type: "POST",
        data: ({
            action: "getApplicationByCategory",
            category: cat,
            area: area,
            type: type,
            price: price,
            number_per_page: number_per_page,
            pages: pages
        }),
        datatype: "JSON",
        success: function (data) {
            var q = 0;
            if (type == "Rating") q = 3;
            else if (type == "Date") q = 4;
            else q = 5;
            appendApps(pagename, data, div, cat, '', pages, q);
            if (bool && div == "topPaidMP") end_view("Loading...");
        }
    });
}

function placeAppByCat(cat) {
    block_view("Loading...");
    $("#topFreeMR").attr("innerHTML", "");
    $("#topFreeMP").attr("innerHTML", "");
    $("#topFreeHR").attr("innerHTML", "");
    $("#topPaidMR").attr("innerHTML", "");
    $("#topPaidMP").attr("innerHTML", "");
    $("#topPaidHR").attr("innerHTML", "");
    getApplicationByCategory(cat, "Rating", area, "FREE", "topFreeHR", 10, 1, true);
    getApplicationByCategory(cat, "Date", area, "FREE", "topFreeMR", 10, 1, true);
    getApplicationByCategory(cat, "DownloadCounter", area, "FREE", "topFreeMP", 10, 1, true);
    getApplicationByCategory(cat, "Rating", area, "PAID", "topPaidHR", 10, 1, true);
    getApplicationByCategory(cat, "Date", area, "PAID", "topPaidMR", 10, 1, true);
    getApplicationByCategory(cat, "DownloadCounter", area, "PAID", "topPaidMP", 10, 1, true);

    $("#rightMenuContent a").removeClass("mainright_text_select").addClass("mainright_text");
    $("#cat" + cat).addClass("mainright_text_select");
}

function getMostRecentApps(pagename, area, price, number_per_page, pages) {
    $.ajax({
        url: serverpath + '/getMostRecentApps',
        type: "POST",
        data: ({
            action: "getMostRecentApps",
            area: area,
            price: price,
            number_per_page: number_per_page,
            pages: pages
        }),
        datatype: "JSON",
        success: function (data) {

            if (data.status == "success") {
                var jsonobj = data.result;
                if (price == "FREE") appendApps(pagename, data, "topFreeMR", -1, '', pages, 0);
                else appendApps(pagename, data, "topPaidMR", -1, '', pages, 0);
            }
        }
    });
}

function getMostPopularApps(pagename, area, price, number_per_page, pages) {
    $.ajax({
        url: serverpath+'/getMostPopularApps',
        type: "POST",
        data: ({
            action: "getMostPopularApps",
            area: area,
            price: price,
            number_per_page: number_per_page,
            pages: pages
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;
               // alert(jsonobj);
                if (price == "FREE") appendApps(pagename, data, "topFreeMP", -1, '', pages, 1);
                else appendApps(pagename, data, "topPaidMP", -1, '', pages, 1);
            }
        }
    });
}

function getMostRatedApps(pagename, area, price, number_per_page, pages) {
    $.ajax({
        url: serverpath+'/getMostRatedApps',
        type: "POST",
        data: ({
            action: "getMostRatedApps",
            area: area,
            price: price,
            number_per_page: number_per_page,
            pages: pages
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;
               // alert(jsonobj);
                if (price == "FREE") appendApps(pagename, data, "topFreeHR", -1, '', pages, 2);
                else appendApps(pagename, data, "topPaidHR", -1, '', pages, 2);
            }
        }
    });
}

function appendApps(pagename, data, div, cat, k, pages, type) {
    // data = '{"status":"success","result":[]}';
    var jsonobj = data.result;
    $("#" + div).attr("innerHTML", "");
    var innerHtml = "";

    if (pagename == "ISYMRKEN") {

        var arr = new Array(10);
        for (var i = 0; i < jsonobj.length; i++) {
            arr[i] = new Array(4);
            arr[i][0] = jsonobj[i].name.substr(0,35);
            arr[i][1] = jsonobj[i].description;
            arr[i][2] = "/Application/Detail/" + jsonobj[i].id;
            arr[i][3] = "<img width=\"49\" height=\"49\" class=\"image60\" alt=\"\" src=\"" + jsonobj[i].icon + "?" + guid() + "\"/>";
        }
        if (jsonobj.length < 10) {
            for (var i = jsonobj.length; i < 10; i++) {
                arr[i] = new Array(4);
                // arr[i][0] = "default images";
                // arr[i][1] = "";
                // arr[i][2] = "#";
                // arr[i][3] = "images/image49x49.jpg";
                arr[i][0] = "";
                arr[i][1] = "";
                arr[i][2] = "";
                arr[i][3] = "";
            }
        }

        var navNum = 1;
        switch (div) {
        case "topFreeMR":
            navNum = 1;
            break;
        case "topFreeMP":
            navNum = 2;
            break;
        case "topFreeHR":
            navNum = 3;
            break;
        case "topPaidMR":
            navNum = 4;
            break;
        case "topPaidMP":
            navNum = 5;
            break;
        case "topPaidHR":
            navNum = 6;
            break;
        default:
            navNum = 1;
            break;
        }

        // apply Most Recent Apps
        innerHtml = "<table style=\"width:680px;\" cellspacing=\"0\" cellpadding=\"10\" border=\"0\" class=\"mainleft_ap\">";
        innerHtml += "<tr><td height=\"20px\"></td></tr>";
        innerHtml += "<tr valign=\"top\">";
        for (var i = 0; i < 5; i++)
        innerHtml += "<td align=\"center\"><a style=\"height:100px; overflow:hidden;\" class=\"mainleft_ap_text\" target=\"_parent\" href=\"" + arr[i][2] + "\">" + arr[i][3] + "<br>" + arr[i][0] + "</a></td>";
        innerHtml += "<td valign=\"bottom\" width=\"30px\"><!--<a target=\"_parent\" href=\"/Application/List?nav=" + navNum + "\"><img height=\"17\" width=\"8\" border=\"0\" alt=\"more\" style=\"display:" + ((jsonobj.length == 0) ? "none" : "inline") + "\" src=\"../../Content/images/NewPicSet_more.gif\"></a>--></td>";
        innerHtml += "</tr>";
        innerHtml += "<tr><td height=\"20px\"></td></tr>";
        innerHtml += "<tr valign=\"top\">";
        for (var i = 5; i < 10; i++)
        innerHtml += "<td align=\"center\"><a style=\"height:100px; overflow:hidden;\" class=\"mainleft_ap_text\" target=\"_parent\" href=\"" + arr[i][2] + "\">" + arr[i][3] + "<br>" + arr[i][0] + "</a></td>";
        innerHtml += "<td>&nbsp;</td>";
        innerHtml += "</tr>";
        innerHtml += "<tr><td height=\"20px\"></td></tr>";
        innerHtml += "</table>";

        $("#" + div).empty();
        $("#" + div).append(innerHtml);
    } else {
        var page = ((jsonobj.length % 10) == 0) ? parseInt(jsonobj.length / 10) : (parseInt(jsonobj.length / 10) + 1);
        for (var i = 0; i < page; i++) {
            innerHtml += "<br/><table width=\"100%\" id=\"" + div + "Page" + (parseInt(i) + 1) + "\" style=\"display:" + ((i == 0) ? "inline" : "none") + ";\" class=\"content_class\"><tr><td>";
            innerHtml += "<ul>";
            for (var key = ((i * 10) == 0) ? 0 : (i * 10); key < ((i * 10) + 10); key++) {
                if (key == jsonobj.length) break;
                innerHtml += "<li class=\"ap_description\">";
                innerHtml += "<a target=\"_parent\" href=\"/Application/Detail/" + jsonobj[key].id + "\">";
                innerHtml += "<img width=\"49\" height=\"49\" border=\"0\" class=\"image_flotleft\" alt=\"\" src=\"" + jsonobj[key].icon + "?" + guid() + "\"></a>";
                if (jsonobj[key].name.length > 35) {
                    innerHtml += "<a class=\"ap_name\" target=\"_parent\" href=\"/Application/Detail/" + jsonobj[key].id + "\">" + jsonobj[key].name.substr(0, 35) + "....</a> <br/>";
                } else {
                    innerHtml += "<a class=\"ap_name\" target=\"_parent\" href=\"/Application/Detail/" + jsonobj[key].id + "\">" + jsonobj[key].name + "</a> <br/>";
                }
                innerHtml += "by " + jsonobj[key].authorName.substring(0, 24) + "<br>";
                //innerHtml += ((jsonobj[key].description.split("<br \/>").length>2)?((jsonobj[key].description.split("<br \/>")[0]+"<br />"+jsonobj[key].description.split("<br \/>")[1]).substring(0, 30)):jsonobj[key].description.substring(0, 30)) + " <br/>";      
                if (div.indexOf("Paid") != -1) innerHtml += "Price: US$" + jsonobj[key].price + "<br/>";
                innerHtml += "Download: " + jsonobj[key].downloadnumber + "<br/>";
                innerHtml += viewRateResult(jsonobj[key].rating);
                innerHtml += "(" + jsonobj[key].ratingCounter + ")";
                innerHtml += "</li>";
            }
            innerHtml += "</ul>";
            innerHtml += "</tr></td></table>";
        }

        if (k != '') {
            $.ajax({
                url: serverpath+'/queryAppAmount',
                type: "POST",
                data: ({
                    action: "queryAppAmount",
                    area: area,
                    price: ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"),
                    keyword: k
                }),
                datatype: "JSON",
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;

                        type = (div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID";

                        if(jsonobj.amount > 0){
                            if(type=="FREE" && div=="topFreeHR"){
                                navigatePrice("free", "paidImg_Load", "freeImg_Load", "FreeApp", "PaidApp");
                            }else if(type=="PAID" && div=="topPaidHR"){
                                navigatePrice("paid", "freeImg_Load", "paidImg_Load", "PaidApp", "FreeApp");
                            }
                        }

                        if (jsonobj.length > 10) {

                            var totalPage = parseInt((jsonobj.length % 10 == 0) ? (jsonobj.length / 10) : (jsonobj.length / 10) + 1);
                            innerHtml += "<table width=\"680\" style=\"text-align:center;\"><tr>";
                            innerHtml += "<td align=\"center\" class=\"topage\"> ";
                            innerHtml += "<img id=\"" + div + "pre\" onclick=\"navigatePage((parseInt($(\'#" + div + "pager\').val())-1),'" + div + "'," + totalPage + "," + type + "," + cat + ",'" + k + "');\" style=\"display:" + ((pages == 1) ? "none" : "inline") + ";\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_left.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                            innerHtml += "<img id=\"" + div + "nex\" onclick=\"navigatePage((parseInt($(\'#" + div + "pager\').val())+1),'" + div + "'," + totalPage + "," + type + "," + cat + ",'" + k + "');\" style=\"display:" + ((pages == totalPage) ? "none" : "inline") + ";\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_right.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                            innerHtml += "/ to page";
                            innerHtml += "<select id=\"" + div + "pager\" onChange=\"navigatePage((parseInt($(\'#" + div + "pager\').val())),'" + div + "'," + totalPage + "," + type + "," + cat + ",'" + k + "');\">";
                            for (var i = 1; i <= totalPage; i++)
                            innerHtml += "<option " + ((i == pages) ? "selected='true'" : "") + " >" + i + "</option>";
                            innerHtml += "</select>";
                            innerHtml += "</td>";
                            innerHtml += "</tr></table>";
                        }

                        $("#" + div).empty();
                        $("#" + div).append(innerHtml);
                    }
                }
            });
        } else {
        $.ajax({
            url: serverpath + '/getAppListAmount',
            type: "POST",
            data: ({
                action: "getAppListAmount",
                area: area,
                price: ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"),
                category: cat
            }),
            datatype: "JSON",
            success: function (data) {
                if (data.status == "success") {
                    var jsonobj = data.result;
                    //alert(jsonobj.length);

                    if (jsonobj.amount > 10) {

                        var totalPage = parseInt((jsonobj.amount % 10 == 0) ? (jsonobj.amount / 10) : (jsonobj.amount / 10) + 1);
                        innerHtml += "<table width=\"680\" style=\"text-align:center;\"><tr>";
                        innerHtml += "<td align=\"center\" class=\"topage\"> ";
                        innerHtml += "<img id=\"" + div + "pre\" onclick=\"navigatePage((parseInt($(\'#" + div + "pager\').val())-1),'" + div + "'," + totalPage + "," + type + "," + cat + ",'" + k + "');\" style=\"display:" + ((pages == 1) ? "none" : "inline") + ";\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_left.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                        innerHtml += "<img id=\"" + div + "nex\" onclick=\"navigatePage((parseInt($(\'#" + div + "pager\').val())+1),'" + div + "'," + totalPage + "," + type + "," + cat + ",'" + k + "');\" style=\"display:" + ((pages == totalPage) ? "none" : "inline") + ";\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_right.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                        innerHtml += "/ to page";
                        innerHtml += "<select id=\"" + div + "pager\" onChange=\"navigatePage((parseInt($(\'#" + div + "pager\').val())),'" + div + "'," + totalPage + "," + type + "," + cat + ",'" + k + "');\">";
                        for (var i = 1; i <= totalPage; i++)
                            innerHtml += "<option " + ((i == pages) ? "selected='true'" : "") + " >" + i + "</option>";
                        innerHtml += "</select>";
                        innerHtml += "</td>";
                        innerHtml += "</tr></table>";
                    }

                    $("#" + div).empty();
                    $("#" + div).append(innerHtml);
                }
            }
        });
        }
    }
}

function navigatePage(page, div, totalPage, type, cat, k) {

    switch (type) {
    case 0:
        getMostRecentApps(pagename, area, ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), 10, page);
        break;
    case 1:
        getMostPopularApps(pagename, area, ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), 10, page);
        break;
    case 2:
        getMostRatedApps(pagename, area, ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), 10, page);
        break;
    case 3:
        getApplicationByCategory(cat, "Rating", area, ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), div, 10, page, false);
        break;
    case 4:
        getApplicationByCategory(cat, "Date", area, ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), div, 10, page, false);
        break;
    case 5:
        getApplicationByCategory(cat, "DownloadCounter", area, ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), div, 10, page, false);
        break;
    case 6:
        queryAppType(k, "Rating", ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), div, 10, page, false);
        break;
    case 7:
        queryAppType(k, "Date", ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), div, 10, page, false);
        break;
    case 8:
        queryAppType(k, "DownloadCounter", ((div.toLowerCase().indexOf("paid") == -1) ? "FREE" : "PAID"), div, 10, page, false);
        break;
    }
}

function getAppsDetail(area) {
    var item_id = jQuery.url.attr("directory").split('/')[3];
    //alert(jQuery.url.attr("directory").split('/')[3]);
    $.ajax({
        url: serverpath+'/getAppDetail',
        type: "POST",
        data: ({
            action: "getAppDetail",
            area: area,
            appid: item_id
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj =data.result;

                if (jsonobj.name.length > 38) {
                    $("#detailHead").attr("innerHTML", jsonobj.name.substr(0, 38) + "....");
                }else{
                    $("#detailHead").attr("innerHTML", jsonobj.name.substr(0, 38));
                }
                $("#author").attr("innerHTML", jsonobj.authorName);
                $("#date").attr("innerHTML", jsonobj.updateDate);

                var scnList = jsonobj.screenShot.split(',');
                var innerHtml = "";
                for (var i = 0; i < scnList.length; i++)
            //    innerHtml += "<li><a target=\"_blank\" href=\"" + scnList[i] + "?" + guid() + "\"><img height=\"245\" width=\"440\" class=\"image440x245\" src=\"" + scnList[i] + "?" + guid() + "\" /></a></li>";
                innerHtml += "<li><a target=\"_blank\" href=\"" + scnList[i] + "?" + guid() + "\"><img class=\"image440x245\" src=\"" + scnList[i] + "?" + guid() + "\" /></a></li>";
                $("#slidetexts").append(innerHtml);

                var headHtml = "<script type='text/javascript'>";
                headHtml += "slideLine('slidetexts', 5500, 32, 20);";
                headHtml += "</script>";
                $('head').append(headHtml);
								
                $("#votenum").attr("innerHTML", jsonobj.ratingCounter);
                $("#rating").attr("innerHTML", Math.round(jsonobj.rating*100)/100);
                $("#price").attr("innerHTML", jsonobj.price);
                //jsonobj.icon = "http://icon.com/j.jpg";
                $("#icon_scn").attr("src", jsonobj.icon + "?" + guid());
                $("#categories").attr("innerHTML", jsonobj.category);
                
                $("#description").empty();
                $("#description").append(jsonobj.description.replace(/\r\n\r\n/g, "<br/>"));
                
                $("#rateView").attr("innerHTML", viewRateResult(jsonobj.rating));
                $("#version").attr("innerHTML", jsonobj.version);
                if (parseInt(jsonobj.price) > 0) $("#downloadBtn").attr("src", "../../Content/images/purchase.gif");
                

                getAppReview();
            }
        }
    });
}

function getAppReview() {
    var appid = jQuery.url.attr("directory").split('/')[3];
    $.ajax({
        url: serverpath+'/getReview',
        type: "POST",
        data: ({
            action: "getReview",
            username: "",
            userid: "",
            appid: appid
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;
                var innerHtml = "";

                if (jsonobj.length == 0) {
                    $("#reviewDiv").css("display", "none");
                    return;
                }

                for (key in jsonobj) {
                    innerHtml += "<tr>";
                    innerHtml += "<td width=\"12\" valign=\"top\">&nbsp; </td>";
                    innerHtml += "<td width=\"519\" valign=\"top\">" + jsonobj[key].account + "<br>";
                    innerHtml += "<span class=\"text_lightgray\">Posted: " + jsonobj[key].date + "</span> <br>";
                    innerHtml += jsonobj[key].comment;
                    innerHtml += "</td>";
                    innerHtml += "<td width=\"143\" valign=\"top\">Rate:";
                    innerHtml += viewRateResult(jsonobj[key].rating);
                    innerHtml += "</td>";
                    innerHtml += "</tr>";

                    if (parseInt(key) != (jsonobj.length - 1)) innerHtml += "<tr><td colspan=\"3\"><hr color=\"#d1e19c\" width=\"98%\"></td></tr>";
                }

                $("#reviewContent").append(innerHtml);
            }
        }
    });
}

function downloadApp(price, downloadUrl) {
    if (price != 0) {
        $.ajax({
            url: "/Handle/iniSession",
            type: "POST",
            data: ({
                act: "iniSession"
            }),
            success: function (data) {
                if (data == "guest") openLoginDialog();
                else window.location = downloadUrl;
            }
        });
    } else window.location = downloadUrl;
}

function getMemberAppDetail() {
    var item_id = jQuery.url.attr("directory").split('/')[3];

    $.ajax({
        url: serverpath+'/getAppDetail',
        type: "POST",
        data: ({
            action: "getAppDetail",
            area: area,
            appid: item_id
        }),
        datatype: "JSON",
        success: function (data) {

            if (data.status == "success") {

                var json = data.result;

                $("#icon_scn").attr("innerHTML", "<img width=\"145\" height=\"77\" border=\"0\" alt=\"\" src=\"" + json.icon + "?" + guid() + "\" />");
                $("#rateView").attr("innerHTML", viewRateResult(json.rating));
                $("#rating").attr("innerHTML", json.ratingCounter);
                $("#detailHead").attr("innerHTML", json.name);
                $("#title").attr("innerHTML", json.name);
                $("#apHref").attr("href", "/Application/Detail/" + item_id);
                $("#description").append(json.description.replace(/\r\n\r\n/g, "<br/>"));
                $("#date").attr("innerHTML", json.updateDate);
                $("#votenum").attr("innerHTML", json.downloadNumber);
                $("#price").attr("innerHTML", json.price);


                getReview();

            }
        }
    });
}

function getSupportFiles(timestamp, area) {
    $.ajax({
        url: serverpath+'/getSupportFiles',
        type: "POST",
        data: ({
            action: "getSupportFiles",
            area: area,
            timestamp: timestamp
        }),
        datatype: "JSON",
        success: function (data) {
            var faqType = new Array();
            if (data.status == "success") {
                var jsonobj = (data.result);

                // get Type
                for (key in jsonobj) {
                    faqType[key] = jsonobj[key].q.split(']')[0] + "]";
                }
                faqType = unique(faqType);

                // generate Type Div
                for (key in faqType) {
                    var innerHtml = "<div id=\"" + faqType[key].replace("[", "").replace("]", "").replace(/\ /g, "") + "\">";
                    innerHtml += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"faq_q\">";
                    innerHtml += "<tr>";
                    innerHtml += "<td valign=\"top\">";
                    innerHtml += "<img width=\"24\" height=\"24\" align=\"absbottom\" class=\"faq_image\" alt=\"\" src=\"../../Content/images/icon_q.gif\">";
                    innerHtml += "<a class=\"faq_textbig\" href=\"javascript:slideToggle('" + faqType[key].replace("[", "").replace("]", "").replace(/\ /g, "") + "S" + "',500);\">" + faqType[key] + "</a>";
                    innerHtml += "</td>";
                    innerHtml += "</tr>";
                    innerHtml += "</table>";
                    innerHtml += "</div>";
                    innerHtml += "<div id=\"" + faqType[key].replace("[", "").replace("]", "").replace(/\ /g, "") + "S" + "\" style=\"display:none;\"></div>";

                    $("#faqDiv").append(innerHtml);
                }

                // generate Question and Answer Table
                for (key in jsonobj) {
                    // Question
                    var qHtml = "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"faq_q\">";
                    qHtml += "<tr>";
                    qHtml += "<td style=\"cursor:pointer;\" valign=\"top\" onclick=\"slideToggle('f" + key + "',300)\" class=\"faq_text\">";
                    qHtml += faqType[key] = jsonobj[key].q.split(']')[1].substring(1);
                    qHtml += "</td>";
                    qHtml += "<td valign=\"top\" align=\"right\">";
                    qHtml += "</td>";
                    qHtml += "</tr>";
                    qHtml += "</table>";
                    $("#" + (jsonobj[key].q.split(']')[0] + "]").replace("[", "").replace("]", "").replace(/\ /g, "") + "S").append(
                    qHtml);

                    // Answer
                    var aHtml = "<table id=\"f" + key + "\" style=\"display:none; width:600px;\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"faq_a\">";
                    aHtml += "<tr>";
                    aHtml += "<td width=\"35\" valign=\"top\">&nbsp;</td>";
                    aHtml += "<td valign=\"top\">";
                    aHtml += "<img width=\"24\" height=\"24\" class=\"faq_image\" alt=\"\" src=\"../../Content/images/icon_qa.gif\"/>";
                    aHtml += "</td>";
                    aHtml += "<td>";
                    aHtml += jsonobj[key].a;
                    aHtml += "</td>";
                    aHtml += "</tr>";
                    aHtml += "</table>";
                    $("#" + (jsonobj[key].q.split(']')[0] + "]").replace("[", "").replace("]", "").replace(/\ /g, "") + "S").append(
                    aHtml);
                }
            }
        }
    });
}

function slideToggle(div, speed) {
    $("#" + div).slideToggle(speed);
}

function unique(arrayName) {
    var newArray = new Array();
    label: for (var i = 0; i < arrayName.length; i++) {
        for (var j = 0; j < newArray.length; j++) {
            if (newArray[j] == arrayName[i]) continue label;
        }
        newArray[newArray.length] = arrayName[i];
    }
    return newArray;
}

function initailizeUserVerification() {
    block_view("Processing...");
    // email
    if ($.trim($("#verify_mail").val()).length == 0) {
        $("#verifyError").attr("innerHTML", "Please fill E-Mail Address!");
        window.location = "#";
        end_view("Processing...");
        return;
    }

    var recaptcha_challenge_field = $("#recaptcha_challenge_field").val();
    var recaptcha_response_field = $("#recaptcha_response_field").val();
    $.ajax({
        url: "/Handle/captcha",
        type: "POST",
        data: ({
            act: "captcha",
            recaptcha_challenge_field: recaptcha_challenge_field,
            recaptcha_response_field: recaptcha_response_field
        }),
        success: function (data) {
            if (data == "success") {
                $.ajax({
                    url: serverpath + '/getUserProfileByUserName',
                    type: "POST",
                    data: ({
                        action: "getUserProfileByUserName",
                        operation: "initailizeUserVerification",
                        username: $.trim($("#verify_mail").val())
                    }),
                    datatype: "JSON",
                    success: function (data) {
                        if (data.status == "success") {
                            var jsonobj = data.result;
                            if (jsonobj[0].status == 2) {
                                $.ajax({
                                    url: serverpath + '/initializeUserVerification',
                                    type: "POST",
                                    data: ({
                                        action: "initializeUserVerification",
                                        area: area,
                                        userid: jsonobj[0].user_id
                                    }),
                                    datatype: "JSON",
                                    success: function (
                                    data) {
                                        if (data.status == "success") {
                                            var innerHtml = "<tr>";
                                            innerHtml += "<td width=\"88%\" align=\"left\"><span style=\"padding-left:30px;\" class=\"error_text\">The verification mail have been sent successfully!</span>";
                                            innerHtml += "</td></tr>";
                                            $("#verify_content").empty();
                                            $("#verify_content").append(
                                            innerHtml);
                                            window.location = "#";
                                        }
                                        end_view("Processing...");
                                    }
                                });
                            } else {
                                $("#verifyError").attr("innerHTML", "The email you fill has already been activated!");
                                window.location = "#";
                                end_view("Processing...");
                            }
                        } else {
                            $("#verifyError").attr("innerHTML", "The email you fill doesn't exist!");
                            window.location = "#";
                            end_view("Processing...");
                        }
                    }
                });
            } else {
                $("#verifyError").attr("innerHTML", "Incorrect confirmation code!");
                window.location = "#";
                Recaptcha.reload();
                $("#recaptcha_response_field").val("");
                $("#recaptcha_response_field").focus();
                end_view("Processing...");
            }
        }
    });
}

function addContactRequest() {
    block_view("Processing...");
    // contact name
    if ($.trim($("#con_name").val()).length == 0) {
        $("#contactError").attr("innerHTML", "Please fill your name!");
        window.location = "#";
        end_view("Processing...");
        return;
    }

    // email name
    if ($.trim($("#con_mail").val()).length == 0) {
        $("#contactError").attr("innerHTML", "Please fill your email!");
        window.location = "#";
        end_view("Processing...");
        return;
    }

    // email format
    if ((!ismail($("#con_mail").val()))) {
        $("#contactError").attr("innerHTML", "Incorrect email format!");
        window.location = "#";
        end_view("Processing...");
        return;
    }

    // subject
    if ($.trim($("#con_subject").val()).length == 0) {
        $("#contactError").attr("innerHTML", "Please fill your subject!");
        window.location = "#";
        end_view("Processing...");
        return;
    }

    // message
    if ($.trim($("#con_msg").val()).length == 0) {
        $("#contactError").attr("innerHTML", "Please fill your message!");
        window.location = "#";
        end_view("Processing...");
        return;
    }

    var recaptcha_challenge_field = $("#recaptcha_challenge_field").val();
    var recaptcha_response_field = $("#recaptcha_response_field").val();
    $.ajax({
        url: "/Handle/captcha",
        type: "POST",
        data: ({
            act: "captcha",
            recaptcha_challenge_field: recaptcha_challenge_field,
            recaptcha_response_field: recaptcha_response_field
        }),
        success: function (data) {
            if (data == "success") {

                var now = new Date();
                var publish_time = getTimestamp(now);
                var asker = $("#con_name").val();
                var asker_email = $("#con_mail").val();
                var subject = $("#con_subject").val();
                var msg = $("#con_msg").val();
                var msg_type = $("#catOption").val();
                var asker_type = -1;

                $.ajax({
                    url: "/Handle/iniSession",
                    type: "POST",
                    data: ({
                        act: "iniSession"
                    }),
                    success: function (data) {
                        if (data != "guest") asker_type = 0;
                        $.ajax({
                            url: serverpath + '/addContactRequest',
                            type: "POST",
                            data: ({
                                action: "addContactRequest",
                                area: area,
                                publish_time: publish_time,
                                asker: asker,
                                asker_email: asker_email,
                                subject: subject,
                                msg: msg,
                                msg_type: msg_type,
                                asker_type: asker_type
                            }),
                            datatype: "JSON",
                            success: function (data) {
                                if (data.status == "success") {
                                    $("#contact_content").css("display", "none");
                                    $("#contactError").attr("innerHTML", "The message has been sent successfully!");
                                    window.location = "#";
                                }else{
                                    $("#contactError").attr("innerHTML", "Fail to send the message! Please try again later!");
                                    window.location = "#";
                                }
                                end_view("Processing...");
                            }
                        });
                    }
                });
            } else {
                $("#contactError").attr("innerHTML", "Incorrect confirmation code!");
                window.location = "#";
                Recaptcha.reload();
                $("#recaptcha_response_field").val("");
                $("#recaptcha_response_field").focus();
              //  $("#captchaImg").attr("src", "/Handle/showcaptcha?" + Math.random());
                end_view("Processing...");
                return;
            }

        }
    });
}

function getTimestamp(date) {
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
}

function registration() {
    // email
    if ($.trim($("#sign_email").val()).length == 0 || (!ismail($("#sign_email").val()))) {
        $("#signError").attr("innerHTML", "Please fill correct E-mail!");
        window.location = "#";
        return;
    } else {
        if ($("#cfEmail_tr").css("display") == "table-row") {
            $.ajax({
                url: serverpath + '/checkUserData',
                type: "POST",
                async: false,
                data: ({
                    action: "checkUserData",
                    field: "Email",
                    value: $.trim($("#sign_email").val())
                }),
                datatype: "JSON",
                success: function (data) {
                    if (data.status == "success") {
                        $("#signError").attr("innerHTML", "Please fill correct E-mail!");
                        window.location = "#";
                        return;
                    }else{
                    
                    // confirm email
    if ($("#sign_email").val() != $("#sign_cfEmail").val() && $("#cfEmail_tr").css("display") == "table-row") {
        $("#signError").attr("innerHTML", "Confirm E-Mail error!");
        window.location = "#";
        return;
    }

    // password
    if (($.trim($("#sign_pwd").val()).length < 6 || $("#sign_pwd").val().toLowerCase().replace(/[^a-z]/g, '').length == 0 || $("#sign_pwd").val().replace(/[^0-9]/g, '').length == 0) && $("#pwd_tr").css("display") == "table-row") {
        $("#signError").attr("innerHTML", "Incorrect password format!");
        window.location = "#";
        return;
    }

    // confirm password
    if ($("#sign_pwd").val() != $("#sign_cfPwd").val() && $("#cfPwd_tr").css("display") == "table-row") {
        $("#signError").attr("innerHTML", "Confirm password error!");
        window.location = "#";
        return;
    }

    // level2 checked
    if ($("#tolevel2Ck").is(":checked")) {
        if ($.trim($("#sign_fname").val()).length == 0) {
            $("#signError").attr("innerHTML", "Please fill your first name!");
            window.location = "#";
            return;
        }

        if ($.trim($("#sign_lname").val()).length == 0) {
            $("#signError").attr("innerHTML", "Please fill your last name!");
            window.location = "#";
            return;
        }

        if ($.trim($("#sign_councode").val()).length == 0 || $.trim($("#sign_areacode").val()).length == 0 || $.trim($("#sign_phone").val()).length == 0) {
            $("#signError").attr("innerHTML", "Please fill your phone number!");
            window.location = "#";
            return;
        }

        if ($("#sign_country").val() == "0") {
            $("#signError").attr("innerHTML", "Please select your country!");
            window.location = "#";
            return;
        }
    }

//    if ($.trim($("#sign_code").val()).length == 0) {
//        $("#signError").attr("innerHTML", "Please fill confirmation code!");
//        window.location = "#";
//        return;
//    }

    // confirmation code
    var recaptcha_challenge_field = $("#recaptcha_challenge_field").val();
    var recaptcha_response_field = $("#recaptcha_response_field").val();
    $.ajax({
        url: "/Handle/captcha",
        type: "POST",
        async: false,
        data: ({
            act: "captcha",
            recaptcha_challenge_field: recaptcha_challenge_field,
            recaptcha_response_field: recaptcha_response_field
        }),
        success: function (data) {
            if (confirm) data = "success";
            if (data != "success") {
                $("#signError").attr("innerHTML", "Incorrect Confirmation Code!");
                Recaptcha.reload();
                $("#recaptcha_response_field").val("");
                $("#recaptcha_response_field").focus();
              //  $("#captchaImg").attr("src", "/Handle/showcaptcha");
                window.location = "#";
                confirm = false;
                return;
            } else {
                confirm = true;
                // agree checkbox
                if (!$("#sign_agree").is(":checked")) {
                    $("#signError").attr("innerHTML", "Please check agree!");
                    window.location = "#";
                    return;
                }


                block_view("Processing...");
                $.ajax({
                    url: "/Handle/iniSession",
                    type: "POST",
                    cache: false,
                    async: false,
                    data: ({
                        act: "iniSession"
                    }),
                    success: function (data) {

                        if (jQuery.url.param("email") !== undefined) {
                            $.ajax({
                                url: serverpath+'/getUserProfileByUserName',
                                type: "POST",
                                async: false,
                                data: ({
                                    action: "getUserProfileByUserName",
                                    username: decodeURIComponent(jQuery.url.param("email"))
                                }),
                                datatype: "JSON",
                                success: function (data) {
                                    if (data.status == "success") {
                                        var jsonobj = data.result;

                                        var mdegree = 1;
                                        if ($("#tolevel2Ck").is(":checked")) mdegree = 2;
                                        var userid = jsonobj[0].user_id;
                                        var firstname = $("#sign_fname").val();
                                        var lastname = $("#sign_lname").val();
                                        var nickname = jsonobj[0].email;
                                        var email = jsonobj[0].email;
                                        var company = $("#sign_company").val();
                                        var address = $("#sign_addr").val();
                                        var postcode = $("#sign_postcode").val();
                                        var phonenumber = jsonobj[0].phone_number;
                                        if ($("#tolevel2Ck").is(":checked")) phonenumber = $("#sign_councode").val() + "-" + $("#sign_areacode").val() + "-" + $("#sign_phone").val();
                                        if ($.trim($("#sign_councode").val()).length != 0 && $.trim($("#sign_areacode").val()).length != 0 && $.trim($("#sign_phone").val()).length != 0) phonenumber = $("#sign_councode").val() + "-" + $("#sign_areacode").val() + "-" + $("#sign_phone").val();
                                        var paypadid = jsonobj[0].paypad_id;
                                        var area = $("#sign_country").val();
                                        var sex = jsonobj[0].gender;
                                        var ddegree = jsonobj[0].ddegree;
                                        var picture = jsonobj[0].picture;
                                        var country = jsonobj[0].country;
                                        if ($("#sign_country").val() != "0") country = $("#sign_country :selected").val();
                                        var timezone = jsonobj[0].timezone;
                                        //if ($("#sign_country").val() != "0") timezone = $("#sign_country :selected").attr("item");
                                        var website = jsonobj[0].website;
                                        var bankname = jsonobj[0].bankname;
                                        var billaccount = jsonobj[0].billaccount;
                                        var bankaba = jsonobj[0].bankABA;
                                        var bankswift = jsonobj[0].bankSWIFT;
                                        var notice1 = jsonobj[0].notice1;
                                        var notice2 = jsonobj[0].notice2;
                                        var status = jsonobj[0].status;
                                        var paymenttype = jsonobj[0].paymenttype;

                                        $.ajax({
                                            url: serverpath + '/setUserProfile',
                                            type: "POST",
                                            data: ({
                                                action: "setUserProfile",
                                                userid: userid,
                                                email: email,
                                                firstname: firstname,
                                                lastname: lastname,
                                                nickname: nickname,
                                                company: company,
                                                phone: phonenumber,
                                                timezone: timezone,
                                                postcode: postcode,
                                                country: country,
                                                website: website,
                                                bankname: bankname,
                                                billaccount: billaccount,
                                                notice1: notice1,
                                                notice2: notice2,
                                                status: status,
                                                ddegree: ddegree,
                                                mdegree: mdegree,
                                                address: address,
                                                paypadid: paypadid,
                                                area: area,
                                                sex: sex,
                                                picture: picture,
                                                bankaba: bankaba,
                                                bankswift: bankswift,
                                                paymenttype: paymenttype
                                            }),
                                            datatype: "JSON",
                                            async: false,
                                            success: function (
                                            data) {
                                                if (data.status == "success") {
                                                    setMemberEULA();
                                                } else {
                                                    $("#signError").attr("innerHTML", "Fail to register, please try again later!");
                                                    window.location = "#";
                                                }
                                                end_view("Processing...");
                                            }
                                        });
                                    }
                                }
                            });
                        } else {

                            var ddegree = 0;
                            var mdegree = 1;
                            if ($("#tolevel2Ck").is(":checked")) mdegree = 2;
                            var useract = $("#sign_email").val();
                            var email = $("#sign_email").val();
                            var userpwd = $("#sign_pwd").val();
                            var firstname = $("#sign_fname").val();
                            var lastname = $("#sign_lname").val();
                            var nickname = $("#sign_email").val();
                            var company = $("#sign_company").val();
                            var phonenumber = "";
                            if ($("#tolevel2Ck").is(":checked")) phonenumber = $("#sign_councode").val() + "-" + $("#sign_areacode").val() + "-" + $("#sign_phone").val();
                            var paypadid = "";
                            var sex = "";
                            var address = $("#sign_addr").val();
                            var postcode = $("#sign_postcode").val();
                            var country = "";
                            if ($("#sign_country").val() != 0) country = $("#sign_country :selected").val();
                            var picture = "";
                            var timezone = "";
                            //if ($("#sign_country").val() != 0) timezone = $("#sign_country :selected").attr("item");
                            var website = "";
                            var bankname = "";
                            var billaccount = "";
                            var notice1 = "";
                            var notice2 = "";
                            var bankaba = "";
                            var bankswift = "";

                            $.ajax({
                                url: serverpath+'/Registration',
                                type: "POST",
                                data: ({
                                    action: "Registration",
                                    ddegree: ddegree,
                                    mdegree: mdegree,
                                    username: useract,
                                    email: email,
                                    password: userpwd,
                                    firstname: firstname,
                                    lastname: lastname,
                                    nickname: nickname,
                                    company: company,
                                    phone: phonenumber,
                                    address: address,
                                    paypadid: paypadid,
                                    sex: sex,
                                    area: area,
                                    country: country,
                                    postcode: postcode,
                                    picture: picture,
                                    timezone: timezone,
                                    website: website,
                                    bankname: bankname,
                                    billaccount: billaccount,
                                    notice1: notice1,
                                    notice2: notice2,
                                    bankaba: bankaba,
                                    bankswift: bankswift
                                }),
                                datatype: "JSON",
                                async: false,
                                success: function (data) {
                                    if (data.status == "success") {
                                        window.location = "/Member/ThankYouForRegistering";
                                    }else if (data.status == "open id success") {
                                        window.location = "/Member/RegistrationFinish";
                                    } else {
                                        $("#signError").attr("innerHTML", "Fail to register, please try again later!");
                                        window.location = "#";
                                    }
                                }
                            });
                        }
                    }
                });

                end_view("Processing...");
            }
        }
    });

                    }
                }
            });
        }
    }
}

function getUserProfileByUserName(useracc) {
    $.ajax({
        url: serverpath+'/getUserProfileByUserName',
        type: "POST",
        data: ({
            action: "getUserProfileByUserName",
            username: useracc
        }),
        datatype: "JSON",
        success: function (data) {
            $("body").append(data);
        }

    });
}

function getUserProfileByUserID() {
    var userid = 172;
    $.ajax({
        url: serverpath+'/getUserProfileByUserID',
        type: "POST",
        data: ({
            action: "getUserProfileByUserID",
            userid: userid
        }),
        datatype: "JSON",
        success: function (data) {
            $("body").append(data);
        }
    });
}

function requestPasswordReset() {

    if ($.trim($("#profile_pwd").val()).length == 0) {
        $("#chgpwdError").attr("innerHTML", "Please fill your old password!");
        return;
    }

    if ($.trim($("#new_pass").val()).length == 0) {
        $("#chgpwdError").attr("innerHTML", "Please fill your new password!");
        return;
    }

    if ($.trim($("#cfnew_pass").val()).length == 0) {
        $("#chgpwdError").attr("innerHTML", "Please confirm your new password!");
        return;
    }

    if ($.trim($("#new_pass").val()).length < 6 || $("#new_pass").val().toLowerCase().replace(/[^a-z]/g, '').length == 0 || $("#new_pass").val().replace(/[^0-9]/g, '').length == 0) {
        $("#chgpwdError").attr("innerHTML", "Incorrect password format!");
        return;
    }

    if ($("#cfnew_pass").val() != $("#new_pass").val()) {
        $("#chgpwdError").attr("innerHTML", "Confirm password incorrect!");
        return;
    }

    block_view("Loading...");
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        data: ({
            act: "iniSession"
        }),
        async: false,
        success: function (data) {
            var useracc = data;
            $.ajax({
                url: serverpath+'/requestAuthentication',
                type: "POST",
                data: ({
                    action: "requestAuthentication",
                    username: data,
                    password: $("#profile_pwd").val()
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        var password = $("#new_pass").val();
                        var reason = "forget it";

                        $.ajax({
                            url: serverpath+'/requestPasswordReset',
                            type: "POST",
                            async: false,
                            data: ({
                                action: "requestPasswordReset",
                                username: useracc,
                                password: password,
                                reason: reason
                            }),
                            datatype: "JSON",
                            success: function (data) {
                                if (data.status == "success") {
                                    $("#change_table").css("display", "none");
                                    $("#change_result_table").css("display", "block");
                                    $("#chgpwdResult").attr("innerHTML", "New password has been changed successfully!");
                                } else $("#chgpwdError").attr("innerHTML", "Can't change your new password, please try again later!");
                            }
                        });

                    } else $("#chgpwdError").attr("innerHTML", "Incorrect old password!");
                }
            });
        }
    });
    end_view("Loading...");
}

function getMyInstallations() {
    block_view("Loading...");
    $.ajax({
        url: "/Handle/iniSession2",
        type: "POST",
        async: false,
        data: ({
            act: "iniSession2"
        }),
        success: function (data) {
/*            $.ajax({
                url: serverpath,
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    var jsonobj = data.result;
*/
                    var user_id = data;
                    // var user_id = 890398;
                    var cid = $("#catOption").val();
                    var pricemin = $("#price_min").val();
                    var pricemax = $("#price_max").val();
                    var kw = $("#kw").val();
                    var start_date = $("#start_date").val();
                    var end_date = $("#end_date").val();

                    $.ajax({
                        url: serverpath+'/getMyInstallations',
                        type: "POST",
                        data: ({
                            action: "getMyInstallations",
                            userid: user_id,
                            category: cid,
                            pricemin: pricemin,
                            pricemax: pricemax,
                            keyword: kw,
                            start_date: start_date,
                            end_date: end_date
                        }),
                        datatype: "JSON",
                        async: false,
                        success: function (data) {
                            if (data.status == "success") {
                                var jsonobj = data.result;
                                var totalpage = parseInt((jsonobj.length % 10 == 0) ? (jsonobj.length / 10) : (jsonobj.length / 10) + 1);

                                $("#install_list").empty();

                                var innerHtml = "";

                                //innerHtml += "<td class=\"ap_description\" align=\"left\" colspan=\"5\" width=\"670\">";
/*
                var innerHtml = "<tr>";
                innerHtml += "<td style=\"text-align:center; width:40px;\" class=\"member_description\">No </td>";
                innerHtml += "<td style=\"text-align:left; width:380px;\" class=\"member_description\">Application Name </td>";
                innerHtml += "<td style=\"text-align:left; width:130px;\" class=\"member_description\">Category </td>";
                innerHtml += "<td style=\"text-align:center; width:120px;\" class=\"member_description\">Installation Time </td>";
                innerHtml += "<td style=\"text-align:center; width:100px;\" class=\"member_description\">Summary </td>";
                innerHtml += "</tr>";
                innerHtml += "<tr>";
                innerHtml += "<td class=\"ap_description\" align=\"left\" colspan=\"5\" width=\"670\">";
                */


                                var page = ((jsonobj.length % 10) == 0) ? parseInt(jsonobj.length / 10) : (parseInt(jsonobj.length / 10) + 1);
                                for (var i = 0; i < page; i++) {
                                    innerHtml += "<table id=\"install_listPage" + (i + 1) + "\" style=\"display:" + ((i == 0) ? "table" : "none") + ";\" width=\"670px\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
                                    innerHtml += "<tr><td style=\"text-align:center; width:40px;\" class=\"member_description\">No </td>";
                                    innerHtml += "<td style=\"text-align:left; width:380px;\" class=\"member_description\">Application Name </td>";
                                    innerHtml += "<td style=\"text-align:left; width:130px;\" class=\"member_description\">Device</td>";
                                    innerHtml += "<td style=\"text-align:left; width:130px;\" class=\"member_description\">history</td>";
                                    innerHtml += "<td style=\"text-align:left; width:130px;\" class=\"member_description\">Category </td>";
                                    innerHtml += "<td style=\"text-align:center; width:120px;\" class=\"member_description\">Installation Time </td>";
                                    //innerHtml += "<td style=\"text-align:center; width:100px;\" class=\"member_description\">Release license </td>";
                                    innerHtml += "<td style=\"text-align:center; width:100px;\" class=\"member_description\">Summary </td>";
                                    innerHtml += "</tr><tr><td height=\"8px\">&nbsp;</td></tr>";
                                    for (var key = ((i * 10) == 0) ? 0 : (i * 10); key < ((i * 10) + 10); key++) {
                                        if (key == jsonobj.length) break;
                                        innerHtml += "<tr class=\"ap_description\">";
                                        innerHtml += "<td style=\"text-align:center; width:40px;\" height=\"24px\">" + (parseInt(key) + 1) + "</td>";
                                        innerHtml += "<td style=\"text-align:left; width:380px;\">" + jsonobj[key].name + " </td>";
                                        innerHtml += "<td style=\"text-align:left; width:130px;\"> </td>";
                                        innerHtml += "<td style=\"text-align:left; width:130px;\"> </td>";
                                        innerHtml += "<td style=\"text-align:left; width:130px;\">" + jsonobj[key].category + " </td>";

                                        innerHtml += "<td style=\"text-align:center; width:120px;\">" + jsonobj[key].lastInstallTime + " </td>";
                                        //innerHtml += "<td style=\"text-align:center; width:100px;\"> </td>";
                                        innerHtml += "<td style=\"text-align:center; width:100px;\">";
                                        innerHtml += "<a target=\"_parent\" href=\"/Application/MyDetail/" + jsonobj[key].id + "\">";
                                        innerHtml += "<img width=\"26\" height=\"24\" border=\"0\" alt=\"Detail\" src=\"../../Content/images/icon_downloadList.gif\"></a>";
                                        innerHtml += "</td>";
                                        innerHtml += "</tr>";
                                        innerHtml += "<tr class=\"ap_description\" valign=\"top\">";
                                        innerHtml += "<td colspan=\"8\" class=\"hr\">&nbsp;</td>";
                                        innerHtml += "</tr><tr><td height=\"8px\">&nbsp;</td></tr>";
                                    }
                                    innerHtml += "</table>";
                                }

                                //innerHtml += "</td>";
                                //innerHtml += "</tr>";
                                if (jsonobj.length > 10) {
                                    innerHtml += "<tr class=\"ap_description\" valign=\"top\">";
                                    innerHtml += "<td colspan=\"7\" align=\"center\">";
                                    innerHtml += "<img id=\"install_list_pre\" onclick=\"prevNavMember('install_list'," + totalpage + ")\" style=\"display:none;\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_left.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                                    innerHtml += "<img id=\"install_list_nex\" onclick=\"nextNavMember('install_list'," + totalpage + ")\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_right.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                                    innerHtml += "/ to page ";
                                    innerHtml += "<select id=\"install_list_pager\" onchange=\"navigateMember('install_list',$(this).val()," + totalpage + ")\">";
                                    for (var i = 1; i <= totalpage; i++)
                                    innerHtml += "<option>" + i + "</option>";
                                    innerHtml += "</select>";
                                    innerHtml += "</td>";
                                    innerHtml += "</tr>";
                                }

                                if (jsonobj.length == 0) innerHtml = "<tr><td><span style=\"color:green; font-size:16px;\">No record!</span></td></tr>";
                                $("#install_list").append(
                                innerHtml);

                            }
                        }
                    });
//                }
//            });
        }
    });
    end_view("Loading...");
}

function getPurchaseHistory() {
    block_view("Loading...");
    $.ajax({
        url: "/Handle/iniSession2",
        type: "POST",
        data: ({
            act: "iniSession2"
        }),
        async: false,
        success: function (data) {
/*            $.ajax({
                url: serverpath,
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    var jsonobj = data.result;
*/
                    var user_id = data;
                    // var user_id=890398;
                    var cid = $("#catOption").val();
                    var kw = $("#kw").val();
                    var start_purchase_date = $("#start_date").val();
                    var end_purchase_date = $("#end_date").val();

                    $.ajax({
                        url: serverpath+'/getMyPurchaseHistory',
                        type: "POST",
                        data: ({
                            action: "getMyPurchaseHistory",
                            userid: user_id,
                            category: cid,
                            start_purchase_date: start_purchase_date,
                            end_purchase_date: end_purchase_date,
                            keyword: kw
                        }),
                        datatype: "JSON",
                        async: false,
                        success: function (data) {
                            if (data.status == "success") {
                                var jsonobj = data.result;
                                var totalpage = parseInt((jsonobj.length % 10 == 0) ? (jsonobj.length / 10) : (jsonobj.length / 10) + 1);
                                $("#purchase_list").empty();
                                var innerHtml = "";

                                //innerHtml += "<td class=\"ap_description\" align=\"center\" colspan=\"8\" width=\"670px\">";
                                var page = ((jsonobj.length % 10) == 0) ? parseInt(jsonobj.length / 10) : (parseInt(jsonobj.length / 10) + 1);
                                for (var i = 0; i < page; i++) {
                                    innerHtml += "<table id=\"purchase_listPage" + (i + 1) + "\" style=\"display:" + ((i == 0) ? "table" : "none") + ";\" width=\"670px\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
                                    innerHtml += "<tr><td style=\"text-align:center; width:40px;\" class=\"member_description\">No </td>";
                                    innerHtml += "<td style=\"text-align:center; width:90px;\" class=\"member_description\">Order number </td>";
                                    innerHtml += "<td style=\"text-align:left; width:110px;\" class=\"member_description\">Application Name </td>";
                                    innerHtml += "<td style=\"text-align:left; width:110px; padding-left:10px;\" class=\"member_description\">Category </td>";
                                    innerHtml += "<td style=\"text-align:left; width:60px;\" class=\"member_description\">Price </td>";
                                    innerHtml += "<td style=\"text-align:left; width:70px;\" class=\"member_description\">Version </td>";
                                    innerHtml += "<td style=\"text-align:left; width:100px;\" class=\"member_description\">Machine </td>";
                                    innerHtml += "<td style=\"text-align:center; width:80px;\" class=\"member_description\">Status </td>";
                                    innerHtml += "</tr><tr><td height=\"8px\">&nbsp;</td></tr>";
                                    for (var key = ((i * 10) == 0) ? 0 : (i * 10); key < ((i * 10) + 10); key++) {
                                        if (key == jsonobj.length) break;
                                        innerHtml += "<tr class=\"ap_description\">";
                                        innerHtml += "<td style=\"text-align:center; width:40px;\" height=\"24px\">" + (parseInt(key) + 1) + "</td>";
                                        innerHtml += "<td style=\"text-align:center; width:90px;\">" + jsonobj[key].id + " </td>";
                                        innerHtml += "<td style=\"text-align:left; width:110px;\">" + jsonobj[key].ap_name + " </td>";
                                        innerHtml += "<td style=\"text-align:left; width:110px; padding-left:10px;\">" + jsonobj[key].category + " </td>";
                                        innerHtml += "<td style=\"text-align:left; width:80px;\">US$" + jsonobj[key].price + " </td>";
                                        innerHtml += "<td style=\"text-align:left; width:70px;\">" + jsonobj[key].version_number + " </td>";
                                        innerHtml += "<td style=\"text-align:left; width:100px;\">" + jsonobj[key].machine + " </td>";
                                        innerHtml += "<td style=\"text-align:center; width:80px;\">" + jsonobj[key].status + " </td>";
                                        innerHtml += "</tr>";
                                        innerHtml += "<tr class=\"ap_description\" valign=\"top\">";
                                        innerHtml += "<td colspan=\"8\" class=\"hr\">&nbsp;</td>";
                                        innerHtml += "</tr><tr><td height=\"8px\">&nbsp;</td></tr>";
                                    }
                                    innerHtml += "</table>";
                                }

                                innerHtml += "</td>";
                                innerHtml += "</tr>";
                                if (jsonobj.length > 10) {
                                    innerHtml += "<tr class=\"ap_description\" valign=\"top\">";
                                    innerHtml += "<td colspan=\"8\" align=\"center\">";
                                    innerHtml += "<img id=\"purchase_list_pre\" onclick=\"prevNavMember('purchase_list'," + totalpage + ")\" style=\"display:none;\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_left.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                                    innerHtml += "<img id=\"purchase_list_nex\" onclick=\"nextNavMember('purchase_list'," + totalpage + ")\" width=\"18\" height=\"18\" src=\"../../Content/images/arrow_right.gif\" class=\"topage\" style=\"cursor:pointer;\"> ";
                                    innerHtml += "/ to page ";
                                    innerHtml += "<select id=\"purchase_list_pager\" onchange=\"navigateMember('purchase_list',$(this).val()," + totalpage + ")\">";
                                    for (var i = 1; i <= totalpage; i++)
                                    innerHtml += "<option>" + i + "</option>";
                                    innerHtml += "</select>";
                                    innerHtml += "</td>";
                                    innerHtml += "</tr>";
                                }

                                if (jsonobj.length == 0) innerHtml = "<tr><td><span style=\"color:green; font-size:16px;\">No record!</span></td></tr>";
                                $("#purchase_list").append(
                                innerHtml);
                            }
                        }
                    });
 //               }
//            });
        }
    });
    end_view("Loading...");
}

function navigateMember(table, page, totalpage) {
    $("#" + table + " table").css("display", "none");
    $("#" + table + "Page" + page).css("display", "table");

    if (page == 1) $("#" + table + "_pre").css("display", "none");
    else $("#" + table + "_pre").css("display", "inline");
    if (page == totalpage) $("#" + table + "_nex").css("display", "none");
    else $("#" + table + "_nex").css("display", "inline");
}

function nextNavMember(table, totalpage) {
    var page = (parseInt($("#" + table + "_pager").val()) + 1);
    $("#" + table + " table").css("display", "none");
    $("#" + table + "Page" + page).css("display", "table");

    if (page == 1) $("#" + table + "_pre").css("display", "none");
    else $("#" + table + "_pre").css("display", "inline");
    if (page == totalpage) $("#" + table + "_nex").css("display", "none");
    else $("#" + table + "_nex").css("display", "inline");

    $("#" + table + "_pager").val(page);
}

function prevNavMember(table, totalpage) {
    var page = (parseInt($("#" + table + "_pager").val()) - 1);
    $("#" + table + " table").css("display", "none");
    $("#" + table + "Page" + page).css("display", "table");

    if (page == 1) $("#" + table + "_pre").css("display", "none");
    else $("#" + table + "_pre").css("display", "inline");
    if (page == totalpage) $("#" + table + "_nex").css("display", "none");
    else $("#" + table + "_nex").css("display", "inline");

    $("#" + table + "_pager").val(page);
}

function checkfield(isValid) {
    if (isValid) return "<img alt=\"\" src=\"../../Content/images/correct.png\" />";
    else return "<img alt=\"\" src=\"../../Content/images/wrong.png\" />";
}

function logout() {
    $.ajax({
        url: "/Handle/logout",
        type: "POST",
        data: ({
            act: "logout"
        }),
        success: function (data) {
            if (data == "success") {
                checkSession();
                window.location.href = "http://"+homeurl+"/Member/Logout";
            }
        }
    });
}

function openMaintainDialog() {
    $.get("../../Content/form/maintain.html", function (data) {
        $("#boxes").remove();
        window.location = "#";
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo(1000, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(1000);

        $("#accField").val("");
        $("#passField").val("");
        $("#accField").focus();

        $(window).resize(function () {
            //Get the A tag
            var id = "#dialog";

            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set height and width to mask to fill up the whole screen
            $('#mask').css({
                'width': maskWidth,
                'height': maskHeight
            });

            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(id).css('top', winH / 2 - $(id).height() / 2);
            $(id).css('left', winW / 2 - $(id).width() / 2);
        });

    });
}

function openLoginDialog() {
    $.get("../../Content/form/login_https.html", function (data) {
        $("#boxes").remove();
        window.location = "#";
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo(1000, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(1000);

        $("#accField").val("");
        $("#passField").val("");
        $("#accField").focus();

        $(window).resize(function () {
            //Get the A tag
            var id = "#dialog";

            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set height and width to mask to fill up the whole screen
            $('#mask').css({
                'width': maskWidth,
                'height': maskHeight
            });

            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(id).css('top', winH / 2 - $(id).height() / 2);
            $(id).css('left', winW / 2 - $(id).width() / 2);
        });

    });
}

function openSignUpDialog() {
    $.get("../../Content/form/signup_https.html", function (data) {
        $("#boxes").remove();
        window.location = "#";
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo(1000, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(1000);

        $("#accField").val("");
        $("#passField").val("");
        $("#accField").focus();

        $(window).resize(function () {
            //Get the A tag
            var id = "#dialog";

            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set height and width to mask to fill up the whole screen
            $('#mask').css({
                'width': maskWidth,
                'height': maskHeight
            });

            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(id).css('top', winH / 2 - $(id).height() / 2);
            $(id).css('left', winW / 2 - $(id).width() / 2);
        });

    });
}

function openDownloadDialog() {
    $.get("../../Content/form/downloadApp.html", function (data) {
        window.location = "#";
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#download_dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(700);
        $('#mask').fadeTo(700, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(700);

        $(window).resize(function () {
            //Get the A tag
            var id = "#download_dialog";

            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set height and width to mask to fill up the whole screen
            $('#mask').css({
                'width': maskWidth,
                'height': maskHeight
            });

            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(id).css('top', winH / 2 - $(id).height() / 2);
            $(id).css('left', winW / 2 - $(id).width() / 2);
        });

    });
}

function openPwdDialog() {
    $.get("../../Content/form/changePwd.html", function (data) {
        window.location = "#";
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#changePwd_dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(700);
        $('#mask').fadeTo(700, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(700);

        $("#profile_pwd").val("");
        $("#new_pass").val("");
        $("#cfnew_pass").val("");
        $("#chgpwdError").attr("innerHTML", "");
        $("#change_table").css("display", "inline");
        $("#change_result_table").css("display", "none");

        $(window).resize(function () {
            //Get the A tag
            var id = "#changePwd_dialog";

            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set height and width to mask to fill up the whole screen
            $('#mask').css({
                'width': maskWidth,
                'height': maskHeight
            });

            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(id).css('top', winH / 2 - $(id).height() / 2);
            $(id).css('left', winW / 2 - $(id).width() / 2);
        });

    });
}

function openDownloadTools(eulaid, resourceid, resourcetype, platform) {
    $.ajax({
        url: "/Handle/iniSession2",
        type: "POST",
        cache: false,
        async: false,
        data: ({
            act: "iniSession2"
        }),
        success: function (data) {
            /*            $.ajax({
            url: serverpath,
            type: "POST",
            data: ({
            action: "getUserProfileByUserName",
            username: data
            }),
            datatype: "JSON",
            async: false,
            success: function (data) {
            if (data.status == "success") {
            var jsonobj = data.result;
            */
            $.ajax({
                url: serverpath + '/queryEULASignUp',
                type: "POST",
                data: ({
                    action: "queryEULASignUp",
                    userid: data,
                    eulaid: eulaid
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.result == "0") {
                        $.get("../../Content/form/download_tools.html", function (
                                    data) {
                            window.location = "#";
                            $("body").append(data);
                            $("body").css("overflow", "hidden");

                            $("#agree_ck").attr("checked", false);
                            $("#agreeLink").css("display", "none");

                            // Get the A tag
                            var id = "#dwn_tools_dialog";

                            // Get the screen height and width
                            var maskHeight = $(document).height();
                            var maskWidth = $(window).width();

                            // Set height and width to mask to
                            // fill up the whole screen
                            $('#mask').css({
                                'width': maskWidth,
                                'height': maskHeight
                            });

                            // transition effect
                            $('#mask').fadeIn(700);
                            $('#mask').fadeTo(700, 0.8);

                            // Get the window height and width
                            var winH = $(window).height();
                            var winW = $(window).width();

                            // Set the popup window to center
                            $(id).css('top', 50);
                            $(id).css('left', winW / 2 - $(id).width() / 2);

                            // transition effect
                            $(id).fadeIn(700);
                            $("#agreeLink").unbind("click");
                            $("#agreeLink").bind("click", function () {
                                setEULASignUp(eulaid, resourceid, resourcetype, platform);
                                //window.location.href = downloadpath + "?eulaid=" + eulaid + "&resourceid=" + resourceid + "&type=" + resourcetype + "&area=" + area + "&class=1&platform=" + platform;
                            });

                            $(window).resize(function () {
                                //Get the A tag
                                var id = "#dwn_tools_dialog";

                                //Get the screen height and width
                                var maskHeight = $(document).height();
                                var maskWidth = $(window).width();

                                //Set height and width to mask to fill up the whole screen
                                $('#mask').css({
                                    'width': maskWidth,
                                    'height': maskHeight
                                });

                                //Get the window height and width
                                var winH = $(window).height();
                                var winW = $(window).width();

                                //Set the popup window to center
                                $(id).css('top', 50);
                                $(id).css('left', winW / 2 - $(id).width() / 2);
                            });
                            //$("#agreeLink").attr("href", downloadpath + "?eulaid=" + eulaid + "&resourceid=" + resourceid + "&type=" + resourcetype + "&area=" + area + "&class=1&platform=" + platform);
                            // $("#agreeLink").attr("href",
                            // "javascript:setEULASignUp('" +
                            // eulaid + "','" + resourceid +
                            // "','" + resourcetype + "','" +
                            // platform + "')");
                        });
                    } else {
                        //alert(data.result);
                         setDownloadRec(eulaid, resourceid, resourcetype, platform);
                    }
                }
            });

            //                    }

            //                }
            //            });
        }
    });
}

function setEULASignUp(eulaid, resourceid, resourcetype, platform) {
    $.ajax({
        url: "/Handle/iniSession2",
        type: "POST",
        cache: false,
        async: false,
        data: ({
            act: "iniSession2"
        }),
        success: function (data) {
/*            $.ajax({
                url: serverpath,
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;
*/
                        $.ajax({
                            url: serverpath+'/setEULASignUp',
                            type: "POST",
                            data: ({
                                action: "setEULASignUp",
                                userid: data,
                                eulaid: eulaid
                            }),
                            datatype: "JSON",
                            async: false,
                            success: function (data) {
                                //getTools();
                                setDownloadRec(eulaid, resourceid, resourcetype, platform);
                                //window.location = "AndAc.php?pageid=ENSUPTLS";
                            }
                        });
/*                    }
                }
            });
*/        }
    });
}

function setDownloadRec(eulaid, resourceid, resourcetype, platform) {
    $.ajax({
        url: "/Handle/iniSession2",
        type: "POST",
        cache: false,
        async: false,
        data: ({
            act: "iniSession2"
        }),
        success: function (data) {
/*            $.ajax({
                url: serverpath,
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;
*/
                        $.ajax({
                            url: serverpath+'/setDownloadRec',
                            type: "POST",
                            data: ({
                                action: "setDownloadRec",
                                userid: data,
                                resourceid: resourceid,
                                resourcetype: resourcetype
                            }),
                            datatype: "JSON",
                            async: false,
                            success: function (data) {
                                //$.download(downloadpath, "eulaid=" + eulaid + "&resourceid=" + resourceid + "&type=" + resourcetype + "&area=" + area + "&class=1&platform=" + platform, "get");
                                //window.open("form/dwn.html?id="+guid()+"&eulaid=" + eulaid + "&resourceid=" + resourceid + "&type=" + resourcetype + "&area=" + area + "&class=1&platform=" + platform,"_blank");
                                //$("#dwn_frame").attr("src","form/dwn.html?id="+guid()+"&eulaid=" + eulaid + "&resourceid=" + resourceid + "&type=" + resourcetype + "&area=" + area + "&class=1&platform=" + platform);
                                window.location.href = downloadpath + "?eulaid=" + eulaid + "&resourceid=" + resourceid + "&type=" + resourcetype + "&area=" + area + "&class=1&platform=" + platform;
                            }
                        });
/*                    }
                }
            });
*/        }
    });
}

function openUpgradeDialog() {
    $.get("../../Content/form/upgrade.html", function (data) {
        window.location = "#";
        //$("#download_boxes").remove();
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#upgrade_dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(700);
        $('#mask').fadeTo(700, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(700);

    });
}

function openEULATools() {
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        cache: false,
        async: false,
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            $.ajax({
                url: serverpath+'/getUserProfileByUserName',
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;

                        $.ajax({
                            url: serverpath+'/queryMemberEULA',
                            type: "POST",
                            data: ({
                                action: "queryMemberEULA",
                                userid: jsonobj[0].user_id
                            }),
                            datatype: "JSON",
                            async: false,
                            success: function (data) {
                                var agree = 1;
                                if (jsonobj[0].mdegree != 0) agree = data.result;
                                if (agree == 0) {
                                    $.get("form/eula.html", function (
                                    data) {
                                        window.location = "#";
                                        $("body").append(
                                        data);
                                        $("body").css("overflow", "hidden");

                                        var id = "#eula_dialog";

                                        var maskHeight = $(
                                        document).height();
                                        var maskWidth = $(
                                        window).width();

                                        $('#mask').css({
                                            'width': maskWidth,
                                            'height': maskHeight
                                        });

                                        $('#mask').fadeIn(700);
                                        $('#mask').fadeTo(700, 0.8);

                                        var winH = $(
                                        window).height();
                                        var winW = $(
                                        window).width();

                                        $(id).css('top', 50);
                                        $(id).css('left', winW / 2 - $(id).width() / 2);

                                        $(
                                        id).fadeIn(
                                        700);
                                        // $("#agreeLink").attr("href",
                                        // "javascript:setMemberEULA()");
                                        $("#agreeLink").bind("click", function () {
                                            setMemberEULA();
                                        });
                                    });
                                } else {
                                    var allowpage = ["ISYMRKEN", "ENDWN", "ENDWNDTL", "ENSUPFAQ", "ENSUPTLS", "ENSUPCNT", "ENABU", "ENPLYPV", "ENPLYMB", "ENNWS", "ENBLG", "ENMBRENDPF", "ENMBRENDMIL", "ENMBRENDAD", "ENMBRENDPH", "ENMBRENDMC", "ENPMSRC", "DVCTPC", "DVDMCA"];
                                    var memberpage = ["ENJONS3E", "ENMBRENDPWS", "ENJONREE", "ENJONSUSE", "ENJONS5", "ENJONS5E", "ENLGOT"];
									
                                    if (jQuery.inArray(
                                    pagename, allowpage) == -1) {
                                        if (jQuery.inArray(
                                        pagename, memberpage) == -1) window.location = "/Home/Index";
                                        else window.location = "AndBk.php?pageid=ENMBRENDMC";
                                    } else window.location = window.location.toString().split('#')[0];
                                }
                            }
                        });

                    }

                }
            });
        }
    });
}

function setMemberEULA() {
    $.ajax({
        url: "/Handle/iniSession2",
        type: "POST",
        cache: false,
        async: false,
        data: ({
            act: "iniSession2"
        }),
        success: function (data) {
/*            $.ajax({
                url: serverpath,
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;
*/
                        $.ajax({
                            url: serverpath+'/setMemberEULA',
                            type: "POST",
                            data: ({
                                action: "setMemberEULA",
                                userid: data
                            }),
                            datatype: "JSON",
                            async: false,
                            success: function (data) {
                                if (pagename == "ENJONS3E") {
                                    window.location = "AndMb.php?pageid=ENJONSUSE&token=";
                                } else {
                                    var allowpage = ["ENDWN", "ENDWNDTL", "ENSUPFAQ", "ENSUPTLS", "ENSUPCNT", "ENABU", "ENPLYPV", "ENPLYMB", "ENNWS", "ENBLG", "ENMBRENDPF", "ENMBRENDMIL", "ENMBRENDAD", "ENMBRENDPH", "ENMBRENDMC", "ENPMSRC", "DVCTPC", "DVDMCA"];
                                    var memberpage = ["ISYMRKEN", "ENJONS3E", "ENMBRENDPWS", "ENJONREE", "ENJONSUSE", "ENJONS5", "ENJONS5E", "ENLGOT"];

                                    if (jQuery.inArray(
                                    pagename, allowpage) == -1) {
                                        if (jQuery.inArray(
                                        pagename, memberpage) == -1) window.location = "/";
                                        else window.location = "AndBk.php?pageid=ENMBRENDMC";
                                    } else window.location = window.location.toString().split('#')[0];
                                }
                            }
                        });
/*                    }
                }
            });
*/        }
    });
}

function login() {
    // vibrate configurations
    var conf = {
        frequency: 5000,
        spread: 7,
        duration: 600
    };

    if ($.trim($("#accField").val()).length == 0 || $.trim($("#passField").val()).length == 0) {
        $("#loginErrSpan").attr("innerHTML", "Please fill E-Mail And Password!");
        $("#loginDiv").vibrate(conf);
    } else {
        block_view("logging");
        $.ajax({
            url: serverpath,
            type: "POST",
            data: ({
                action: "requestAuthentication",
                username: $("#accField").val(),
                password: $("#passField").val()
            }),
            datatype: "JSON",
            success: function (data) {
                if (data.status == "success") {
                    $("#loginErrSpan").attr("innerHTML", "");
                    $("#mask, .window").fadeOut(1000);
                    alert(pagename);
                    openEULATools();
                    // checkSession();
                    end_view("logging");
                } else if (data.status == "notactivated") {
                    $("#loginErrSpan").attr("innerHTML", $("#accountNotActivatedTxt").html());
                    $("#loginDiv").vibrate(conf);
                    end_view("logging");
                } else {
                    $("#loginErrSpan").attr("innerHTML", "Incorrect Email or Password!");
                    $("#loginDiv").vibrate(conf);
                    end_view("logging");
                }

            }
        });
    }
}

function recoveryPassword() {
    block_view("Processing...");
    if ($.trim($("#pws_email").val()).length == 0) {
        $("#pwsError").attr("innerHTML", "Please fill E-Mail Address!");
        end_view("Processing");
        return;
    }
    var recaptcha_challenge_field = $("#recaptcha_challenge_field").val();
    var recaptcha_response_field = $("#recaptcha_response_field").val();

    $.ajax({
        url: "/Handle/captcha",
        type: "POST",
        data: ({
            act: "captcha",
            recaptcha_challenge_field: recaptcha_challenge_field,
            recaptcha_response_field: recaptcha_response_field
        }),
        success: function (data) {
            if (data == "success") {
                var useract = $("#pws_email").val();

                $.ajax({
                    url: serverpath+'/recoveryPassword',
                    type: "POST",
                    data: ({
                        action: "recoveryPassword",
                        username: useract
                    }),
                    datatype: "JSON",
                    async: false,
                    success: function (data) {

                        var innerHtml = "";

                        if (data.status == "success") {
                            innerHtml = "<tr><td width=\"12%\">&nbsp;</td>";
                            innerHtml += "<td width=\"88%\" align=\"left\" class=\"login_font13\">";
                            innerHtml += "<span style=\"color:red;\">The password sent successfully!</span>";
                            innerHtml += "</td></tr>";
                        } else {
                            innerHtml = "<tr><td width=\"12%\">&nbsp;</td>";
                            innerHtml += "<td width=\"88%\" align=\"left\" class=\"login_font13\">";
                            innerHtml += "<span style=\"color:red;\">Fail to sent your password, please confirm your email and resent your password!</span><br/>";
                            innerHtml += "<a class=\"about_link\" href=\"AndMb.php?pageid=ENMBRENDPWS\">Resent my password</a>";
                            innerHtml += "</td></tr>";
                        }
                        $("#pwdForm").empty();
                        $("#pwdForm").append(innerHtml);

                    }
                });

                $("#pwsError").attr("innerHTML", "");
            } else {
                $("#pwsError").attr("innerHTML", "Incorrect Confirmation Code!");
                Recaptcha.reload();
                $("#recaptcha_response_field").val("");
                $("#recaptcha_response_field").focus();
            }

        }
    });

    end_view("Processing...");
}

function viewRateResult(rating) {
		if(rating==null||rating=="null"||rating=="") rating=0;
    var full = (rating.toString().split('.').length > 1) ? parseInt(rating.toString().split('.')[0]) : rating;
    var half = (rating.toString().split('.').length > 1) ? parseInt(rating.toString().split('.')[1].substring(0, 1)) : 0;
    var empty = 5 - full;
    if (half >= 5) empty--;

    var innerHtml = "";
    for (var i = 0; i < full; i++)
        innerHtml += "<img height=\"20\" width=\"20\" src=\"../../Content/images/star_full.gif\">";
    if (half >= 5) innerHtml += "<img height=\"20\" width=\"20\" src=\"../../Content/images/star_half.gif\">";
    for (var i = 0; i < empty; i++)
        innerHtml += "<img height=\"20\" width=\"20\" src=\"../../Content/images/star_none.gif\">";

    return innerHtml;
}

function navigateApp(barDiv, srcDiv, noneDiv, inlineDiv) {
    for (var i = 0; i < $("#" + barDiv + " img").length; i++) {
        var str = $("#" + barDiv + " img:eq(" + i + ")").attr("src");
        if (str.substring(str.length - 5, str.length - 4) == "R") $("#" + barDiv + " img:eq(" + i + ")").attr("src", str.substring(0, str.length - 5) + str.substring(str.length - 4, str.length));
    }

    var imgSrc = $("#" + srcDiv).attr("src");
    $("#" + srcDiv).attr("src", imgSrc.substring(0, imgSrc.length - 4) + "R" + imgSrc.substring(imgSrc.length - 4, imgSrc.length));
    $("#" + noneDiv + " div").css("display", "none");
    $("#" + inlineDiv).css("display", "table");

}

function navigatePrice(type, srcLoad, switchLoad, inlineDiv, noneDiv) {
    if (nav != type) {
        var freeSrc = $("#" + srcLoad).attr("src");
        var paidSrc = $("#" + switchLoad).attr("src");
        $("#" + srcLoad).attr("src", freeSrc.substring(0, freeSrc.length - 5) + freeSrc.substring(freeSrc.length - 4, freeSrc.length));
        $("#" + switchLoad).attr("src", paidSrc.substring(0, paidSrc.length - 4) + "R" + paidSrc.substring(paidSrc.length - 4, paidSrc.length));
        $("#" + inlineDiv).css("display", "inline");
        $("#" + noneDiv).css("display", "none");
        nav = type;
    }
}

function getAdvertisementOld() {
    $.ajax({
        url: serverpath+'/getAD',
        type: "POST",
        data: ({
            action: "getAD",
            area: area
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;

                if(jsonobj.length > 0){
                    $("#adTable").css("display", "table");
                    $("#adTableSpace").css("display", "table");
                }

//                if (jsonobj[0].AD_link === undefined) {
//                    $("#adTable").css("display", "none");
//                    $("#adTableSpace").css("display", "none");
//                    return;
//                }

                var innerHtml = "<tr>";
                if (jsonobj.length == 1) {
                    innerHtml += "<td align=\"right\">";
                    innerHtml += "<a href=\"" + jsonobj[0].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[0].icon_link + "?" + guid() + "\" width=\"931\" alt=\"" + jsonobj[0].description + "\" height=\"73\" border=\"0\"/></a>";
                    innerHtml += "</td>";
                    innerHtml += "<td width=\"11\" align=\"left\">&nbsp;</td>";
                } else if (jsonobj.length == 2) {
                    innerHtml += "<td width=\"472\" align=\"right\">";
                    innerHtml += "<a href=\"" + jsonobj[0].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[0].icon_link + "?" + guid() + "\" width=\"455\" alt=\"" + jsonobj[0].description + "\" height=\"73\" border=\"0\"/></a>";
                    innerHtml += "</td>";
                    innerHtml += "<td width=\"21\">";
                    innerHtml += "<img src=\"images/ad_middle.jpg\" alt=\"\" width=\"21\" height=\"93\"></td>";
                    innerHtml += "<td width=\"450\" align=\"center\">";
                    innerHtml += "<a href=\"" + jsonobj[1].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[1].icon_link + "?" + guid() + "\" width=\"455\" alt=\"" + jsonobj[1].description + "\" height=\"73\" border=\"0\"/></a>";
                    innerHtml += "</td>";
                    innerHtml += "<td width=\"12\" align=\"left\">&nbsp;</td>";
                } else if (jsonobj.length > 2) {
                    innerHtml += "<td align=\"right\">";
                    innerHtml += "<a href=\"" + jsonobj[0].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[0].icon_link + "?" + guid() + "\" width=\"295\" alt=\"" + jsonobj[0].description + "\" height=\"73\" border=\"0\"/></a>";
                    innerHtml += "</td>";
                    innerHtml += "<td width=\"21\">";
                    innerHtml += "<img src=\"images/ad_middle.jpg\" alt=\"\" width=\"21\" height=\"93\"></td>";
                    innerHtml += "<td width=\"295\">";
                    innerHtml += "<a href=\"" + jsonobj[1].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[1].icon_link  + "?" + guid()+ "\" width=\"295\" alt=\"" + jsonobj[1].description + "\" height=\"73\" border=\"0\"/></a>";
                    innerHtml += "</td>";
                    innerHtml += "<td width=\"21\">";
                    innerHtml += "<img src=\"images/ad_middle.jpg\" alt=\"\" width=\"21\" height=\"93\"></td>";
                    innerHtml += "<td align=\"left\">";
                    innerHtml += "<a href=\"" + jsonobj[2].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[2].icon_link + "?" + guid() + "\" width=\"295\" alt=\"" + jsonobj[2].description + "\" height=\"73\" border=\"0\"/></a>";
                    innerHtml += "</td>";
                }

                innerHtml += "</tr>";
                $("#adTable").append(innerHtml);
            }
        }
    });
}

function getAdvertisement() {
    $.ajax({
        url: serverpath + '/getAD',
        type: "POST",
        data: ({
            action: "getAD",
            area: area
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;

                if (jsonobj.length > 0) {
                    $("#adTable").css("display", "table");
                    $("#adTableSpace").css("display", "table");
                }

                //                if (jsonobj[0].AD_link === undefined) {
                //                    $("#adTable").css("display", "none");
                //                    $("#adTableSpace").css("display", "none");
                //                    return;
                //                }

                var innerHtml = "<tr>";

                innerHtml += "<td align=\"right\">";

                if (jsonobj.length >= 1) {
                    innerHtml += "<a href=\"" + jsonobj[0].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[0].icon_link + "?" + guid() + "\" width=\"295\" alt=\"" + jsonobj[0].description + "\" height=\"73\" border=\"0\"/></a>";
                } else {
                    innerHtml += "<img src=\"../../Content/images/transparent.gif\" width=\"295\" height=\"73\" border=\"0\"/>";
                }

                innerHtml += "</td>";
                innerHtml += "<td width=\"21\">";
                innerHtml += "<img src=\"../../Content/images/ad_middle.jpg\" alt=\"\" width=\"21\" height=\"93\"></td>";
                innerHtml += "<td width=\"295\">";

                if (jsonobj.length >= 2) {
                    innerHtml += "<a href=\"" + jsonobj[1].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[1].icon_link + "?" + guid() + "\" width=\"295\" alt=\"" + jsonobj[1].description + "\" height=\"73\" border=\"0\"/></a>";
                } else {
                    innerHtml += "<img src=\"../../Content/images/transparent.gif\" width=\"295\" height=\"73\" border=\"0\"/>";
                }

                innerHtml += "</td>";
                innerHtml += "<td width=\"21\">";
                innerHtml += "<img src=\"../../Content/images/ad_middle.jpg\" alt=\"\" width=\"21\" height=\"93\"></td>";
                innerHtml += "<td align=\"left\">";

                if (jsonobj.length >= 3) {
                    innerHtml += "<a href=\"" + jsonobj[2].AD_link + "\" target=\"_blank\">";
                    innerHtml += "<img src=\"" + jsonobj[2].icon_link + "?" + guid() + "\" width=\"295\" alt=\"" + jsonobj[2].description + "\" height=\"73\" border=\"0\"/></a>";
                } else {
                    innerHtml += "<img src=\"../../Content/images/transparent.gif\" width=\"295\" height=\"73\" border=\"0\"/>";
                }
                innerHtml += "</td>";

                innerHtml += "</tr>";
                //alert(innerHtml);
                $("#adTable").html(innerHtml);
            }
        }
    });
}

function getRelatedLink() {
    $.ajax({
        url: serverpath+'/getRelatedLink',
        type: "POST",
        data: ({
            action: "getRelatedLink",
            area: area
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;
                if(jsonobj.length > 0){
                    $("#linkTable").css("display", "table");
                    $("#linkTableSpace").css("display", "table");
                }

//                if (jsonobj[0].icon_link === undefined) {
//                    $("#linkTable").css("display", "none");
//                    $("#linkTableSpace").css("display", "none");
//                    return;
//                }

                for (key in jsonobj) {
                    if (key == 10) return;
                    $("#rlink" + key).attr("href", jsonobj[key].related_link);
                    $("#rimg" + key).attr("src", jsonobj[key].icon_link + "?" + guid());
                }
            }
        }
    });
}

function getReview() {
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            $.ajax({
                url: serverpath+'/getUserProfileByUserName',
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;
                        var username = jsonobj[0].authorName;
                        var userid = jsonobj[0].user_id;
                        var appid = jQuery.url.attr("directory").split('/')[3];
                        $.ajax({
                            url: serverpath+'/getReview',
                            type: "POST",
                            data: ({
                                action: "getReview",
                                username: username,
                                userid: userid,
                                appid: appid
                            }),
                            datatype: "JSON",
                            success: function (data) {
                                if (data.status == "success") {
                                    var jsonobj = data.result;

                                    if (jsonobj.length != 0) {
                                        $("#post_acc").attr("innerHTML", jsonobj[0].account);
                                        $("#post_date").attr("innerHTML", jsonobj[0].date);
                                        $("#post_comment").attr("innerHTML", jsonobj[0].comment);
                                        $("#post_rate").attr("innerHTML", viewRateResult(jsonobj[0].rating));
                                        $("#appReview").css("display", "inline");
                                    } else {
                                        $("#addReview").css("display", "inline");
                                    }
                                }
                            }
                        });
                    }
                }
            });
        }
    });
}

function addReview() {
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            $.ajax({
                url: serverpath + '/getUserProfileByUserName',
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;
                        // $.get('/Handle/Rating?act=get', function (data) {
                        var rate = $(".on").length*0.5;
                        var comment = $("#comment_area").val();
                        var username = jsonobj[0].user_name;
                        var userid = jsonobj[0].user_id;
                        var appid = jQuery.url.attr("directory").split('/')[3];

                        if (rate == "" || rate == "0") {
                            $("#reviewError").attr("innerHTML", "Please rate the application before submit a review!");
                            return;
                        }

                        if (comment == "") {
                            $("#reviewError").attr("innerHTML", "Please fill your comment!");
                            return;
                        }

                        $.ajax({
                            url: serverpath + '/addReview',
                            type: "POST",
                            data: ({
                                action: "addReview",
                                username: username,
                                userid: userid,
                                appid: appid,
                                rate: rate,
                                comment: comment
                            }),
                            datatype: "JSON",
                            success: function (data) {
                                if (data.status == "success") {
                                    $.ajax({
                                        url: "/Handle/unrate",
                                        type: "POST",
                                        data: ({
                                            act: "unrate"
                                        }),
                                        success: function (data) {
                                        }
                                    });
                                    $("#appReview").css("display", "none");
                                    $("#addReview").css("display", "none");
                                    getReview();
                                }

                            }
                        });

                        //});
                    }
                }
            });
        }
    });
}

function getMemberProfile() {
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        cache: false,
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            $.ajax({
                url: serverpath + '/getUserProfileByUserName',
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                success: function (data) {
                    if (data.status == "success") {
                        // data =
                        // '{"status":"success","result":[{"user_id":308,"user_name":"nofortee@vicom.com.tw","first_name":"tee","last_name":"wu","nick_name":"nofortee@livemail.tw","email":"nofortee@livemail.tw","company":"vicom.com","address":"","postcode":"0","phone_number":"886-930-183363","paypad_id":"","area":1,"gender":0,"ddegree":0,"mdegree":1,"token":"OTliZWJkZjcxYTQ0MWQwZTI5ZjY5MGJjMDQxM2U4ZDJlMDM1OGIyOQ==","picture":"http:\/\/140.96.178.108:11152\/vicom_test\/userpic\/308.jpg","country":"USA","timezone":"+0800","website":"","bankname":"","billaccount":"","bankABA":null,"bankSWIFT":null,"notice1":1,"notice2":1,"reg_time":[],"cert_time":[],"status":3}]}';
                        var jsonobj = data.result;

                        if (jsonobj[0].mdegree == 2 || jsonobj[0].ddegree == 1 || jsonobj[0].ddegree == 2) {
                            $("#fname_required").attr("innerHTML", "*");
                            $("#lname_required").attr("innerHTML", "*");
                            $("#country_required").attr("innerHTML", "*");
                        }

                        if (jsonobj[0].mdegree == 2 || jsonobj[0].ddegree == 2) {
                            $("#phone_required").attr("innerHTML", "*");
                        }

                        if (jsonobj[0].mdegree == 2) {
                            $("#tolevel2_tr").css("display", "none");
                        }

                        // picture
                        if (jsonobj[0].picture != "") {
                            $("#profile_img").attr("src", downloadhost + "/" + jsonobj[0].picture + "?" + guid());
                            $("#delete_file").css("display", "inline");
                            $("#cancel_file").css("display", "none");
                        }
                        // email
                        $("#profile_email").attr("innerHTML", jsonobj[0].email);
                        // first name
                        if (jsonobj[0].first_name != "") $("#profile_fname").val(jsonobj[0].first_name);
                        // lase name
                        if (jsonobj[0].last_name != "") $("#profile_lname").val(jsonobj[0].last_name);
                        // company
                        if (jsonobj[0].company != "") $("#profile_company").val(jsonobj[0].company);
                        // phone number
                        if (jsonobj[0].phone_number != "" && jsonobj[0].phone_number != null) {
                            $("#profile_coun").val(
                            jsonobj[0].phone_number.split('-')[0]);
                            $("#profile_area").val(
                            jsonobj[0].phone_number.split('-')[1]);
                            $("#profile_phone").val(
                            jsonobj[0].phone_number.split('-')[2]);
                        }
                        // website
                        if (jsonobj[0].website != "") $("#profile_website").val(jsonobj[0].website);
                        // address
                        if (jsonobj[0].address != "") $("#profile_addr").val(jsonobj[0].address);
                        // postcode
                        if (jsonobj[0].postcode != 0) $("#profile_postcode").val(jsonobj[0].postcode);
                        // country
                        if (jsonobj[0].country != "") {
                            $("#profile_country").val(jsonobj[0].country);
                            //$("#profileError").html($("#profile_country").html());
                            //$("#profile_country :selected").text(jsonobj[0].country);
                        }
                        // timezone
                        //if (jsonobj[0].timezone != "") $("#profile_timezone").val(jsonobj[0].timezone);
                        // language
                        if (jsonobj[0].area != "") $("#profile_lang").val(jsonobj[0].area);
                        // notice1
                        if (jsonobj[0].notice1 != 0) $("#profile_notice1").attr("checked", "true");
                        // notice2
                        if (jsonobj[0].notice2 != 0) $("#profile_notice2").attr("checked", "true");
                    }
                }
            });
        }
    });
}

function getRegistrationProfile() {

    var usermail = decodeURIComponent(jQuery.url.param("email"));

    $.ajax({
        url: serverpath+'/getUserProfileByUserName',
        type: "POST",
        data: ({
            action: "getUserProfileByUserName",
            username: usermail
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;

                if (jsonobj[0].ddegree != 0) $("#toDevBtn").css("display", "none");
                $("#sign_email").attr("readonly", true);
                $("#cfEmail_tr").css("display", "none");
                $("#pwd_tr").css("display", "none");
                $("#pwd_limit_tr").css("display", "none");
                $("#cfPwd_tr").css("display", "none");

                // if already as developer
                if (jsonobj[0].mdegree != 0) {
                    $("body").attr("innerHTML", "");
                    alert("You are already as a member!");
                    window.location = "AndBk.php?pageid=ENMBRENDMC";
                }

                // email
                $("#sign_email").val(jsonobj[0].email);
                // first name
                if (jsonobj[0].first_name != "") $("#sign_fname").val(jsonobj[0].first_name);
                // lase name
                if (jsonobj[0].last_name != "") $("#sign_lname").val(jsonobj[0].last_name);
                // company
                if (jsonobj[0].company != "") $("#sign_company").val(jsonobj[0].company);
                // phone number
                if (jsonobj[0].phone_number != "" && jsonobj[0].phone_number != null) {
                    $("#sign_councode").val(jsonobj[0].phone_number.split('-')[0]);
                    $("#sign_areacode").val(jsonobj[0].phone_number.split('-')[1]);
                    $("#sign_phone").val(jsonobj[0].phone_number.split('-')[2]);
                }
                // address
                if (jsonobj[0].address != "") $("#sign_addr").val(jsonobj[0].address);
                // postcode
                if (jsonobj[0].postcode != 0) $("#sign_postcode").val(jsonobj[0].postcode);
                // country
                if (jsonobj[0].country != "") $("#sign_country").val(jsonobj[0].country);

                $.ajax({
                    url: "/Handle/logout",
                    type: "POST",
                    data: ({
                        act: "logout"
                    }),
                    success: function (data) {
                        if (data == "success") {
                            $.ajax({
                                url: "/Handle/checkSession",
                                type: "POST",
                                data: ({
                                    act: "checkSession"
                                }),
                                success: function (data) {
                                    $("#logDiv").attr("innerHTML", data);
                                }
                            });
                        }
                    }
                });

            }
        }
    });
}

function changeProfilePassword() {
    block_view("Loading...");
    $("#profileError").css("color", "red");
    if ($.trim($("#profile_pwd").val()).length == 0) {
        $("#profileError").attr("innerHTML", "Please fill your old password!");
        window.location = "#";
        end_view("Loading...");
        return;
    } else {
        $("#profileError").attr("innerHTML", "");

        $.ajax({
            url: "/Handle/iniSession",
            type: "POST",
            data: ({
                act: "iniSession"
            }),
            async: false,
            success: function (data) {
                $.ajax({
                    url: serverpath+'/requestAuthentication',
                    type: "POST",
                    data: ({
                        action: "requestAuthentication",
                        username: data,
                        password: $("#profile_pwd").val()
                    }),
                    datatype: "JSON",
                    success: function (data) {
                        if (data.status == "success") $("#profileError").attr("innerHTML", "Correct!");
                        else $("#profileError").attr("innerHTML", "Incorrect password!");
                    }
                });
            }
        });
    }
    end_view("Loading...");
}

function checkUserVerification() {
    var token = jQuery.url.param("token");
    if (token != undefined) {
        $.ajax({
            url: serverpath+'/checkUserVerification',
            type: "POST",
            data: ({
                action: "checkUserVerification",
                token: token
            }),
            datatype: "JSON",
            success: function (data) {
                if (data.status != "success") {
                    $("#signFn_table").attr("innerHTML", "<tr><td class=\"error_text\" align=\"center\">Account verification error, please contact us with your comment!</td></tr>");
                    $("#category").attr("innerHTML", "Fail to verify account");
                } else $("#contentImg_end").css("display", "inline");
            }
        });
    } else $("#contentImg_end").css("display", "inline");
}

function queryApp(keyword) {
    block_view("Quering...");
    $("#topFreeMR").attr("innerHTML", "");
    $("#topFreeMP").attr("innerHTML", "");
    $("#topFreeHR").attr("innerHTML", "");
    $("#topPaidMR").attr("innerHTML", "");
    $("#topPaidMP").attr("innerHTML", "");
    $("#topPaidHR").attr("innerHTML", "");
    queryAppType(keyword, "Rating", "FREE", "topFreeMR", 10, 1, true);
    queryAppType(keyword, "Date", "FREE", "topFreeMP", 10, 1, true);
    queryAppType(keyword, "DownloadCounter", "FREE", "topFreeHR", 10, 1, true);
    queryAppType(keyword, "Rating", "PAID", "topPaidMR", 10, 1, true);
    queryAppType(keyword, "Date", "PAID", "topPaidMP", 10, 1, true);
    queryAppType(keyword, "DownloadCounter", "PAID", "topPaidHR", 10, 1, true);

}

function queryAppType(keyword, type, price, div, number_per_page, pages, bool) {
    $.ajax({
        url: serverpath+'/queryApp',
        type: "POST",
        data: ({
            action: "queryApp",
            keyword: keyword,
            area: area,
            type: type,
            price: price,
            number_per_page: number_per_page,
            pages: pages
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var q = 0;
                if (type == "Rating") q = 6;
                else if (type == "Date") q = 7;
                else q = 8;
                appendApps(pagename, data, div, -1, keyword, pages, q);

                if (div == "topPaidHR" && bool) end_view("Quering...");
            }
        }
    });
}

function checkUserData(field, value, resultSpan) {
    $.ajax({
        url: serverpath+'/checkUserData',
        type: "POST",
        data: ({
            action: "checkUserData",
            field: field,
            value: value
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") $("#" + resultSpan).attr("innerHTML", checkfield(false));
            else {
                $("#" + resultSpan).attr("innerHTML", checkfield(true));
                $("#signError").attr("innerHTML", "");
            }
        }
    });
}

function checkUserData2(field, value, resultSpan) {
    $.ajax({
        url: serverpath+'/checkUserData',
        type: "POST",
        data: ({
            action: "checkUserData",
            field: field,
            value: value
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") $("#" + resultSpan).attr("innerHTML", checkfield(true));
            else {
                $("#" + resultSpan).attr("innerHTML", checkfield(false));
                $("#signError").attr("innerHTML", "");
            }
        }
    });
}

function news(url) {
    window.open(url, "_blank");
    /*
    $.ajax({
        url: "/Hhandle/iniSession",
        type: "POST",
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            if (data == "guest") openLoginDialog();
            else window.open(url, "_blank");
        }
    });
		*/
}

function blog(url) {
    window.open(url, "_blank");
    /*
    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            if (data == "guest") openLoginDialog();
            else window.open(url, "_blank");
        }
    });
		*/
}

function getTools() {
    var platform = 1;
    if ($.client.os == "Android") platform = 1;


    $.ajax({
        url: serverpath + '/getTools',
        type: "POST",
        data: ({
            action: "getTools",
            classes: 1,
            area: area,
            tool_id: "",
            platform: platform
        }),
        datatype: "JSON",
        success: function (data) {
            if (data.status == "success") {
                var jsonobj = data.result;
                var innerHtml = "<table class=\"mainleft\" width=\"100%\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";

                var tools_number = 0;
                for (key in jsonobj) {
                    //alert(jsonobj[key].img_link);
                    if (tools_number == 1) continue;
                    if (jsonobj[key].img_link == '') jsonobj[key].img_link = '../../Content/images/dot.png';
                    innerHtml += "<tr>";
                    innerHtml += "<td valign=\"top\" align=\"left\">";
                    innerHtml += "<table width=\"640px\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
                    innerHtml += "<tr>";
                    innerHtml += "<td height=\"35px\" align=\"left\" colspan=\"2\"><span class=\"text_big02\">" + jsonobj[key].title + "</span></td>";
                    innerHtml += "</tr>";
                    innerHtml += "<tr>";
                    innerHtml += "<td align=\"left\" valign=\"top\"><img width=\"237px\" height=\"177px\" style=\"padding:10px 20px 10px 0px;\" src=\"../../Content/" + jsonobj[key].img_link + "?" + guid() + "\" border=\"0\" /><br/>";



                    innerHtml += "<p class=\"about2\" style=\"text-align: center;margin:0px 20px 10px 0px;\"><a id=\"dwn_href_tools\" href=\"javascript:openDownloadTools('" + jsonobj[key].EULAid + "','" + jsonobj[key].id + "',1,'" + jsonobj[key].platform + "')\" class=\"about_link\" style=\"display:inline;\"><img src=\"../../Content/images/downloadfor250.png\" border=\"0\" /></a></p>";
                    key++;
                    innerHtml += "<p class=\"about2\" style=\"text-align: center;margin:0px 20px 10px 0px;\"><a id=\"dwn_href_tools\" href=\"javascript:openDownloadTools('" + jsonobj[key].EULAid + "','" + jsonobj[key].id + "',1,'" + jsonobj[key].platform + "')\" class=\"about_link\" style=\"display:inline;\"><img src=\"../../Content/images/downloadfor255.png\" border=\"0\" /></a></p>";
                    innerHtml += "<p class=\"about2\" style=\"text-align: center;margin:0px 20px 0px 0px;\"><a id=\"dwn_href_tools\" href=\"javascript:openUtilityDialog()\" class=\"about_link\" style=\"display:inline;\"><img src=\"../../Content/images/downloadforphone.png\" border=\"0\" /></a></p>";
                    // if (tools_number == 0 && jsonobj.length > 1) {
                    //     innerHtml += "<p class=\"about2\" style=\"text-align: center;\"><a id=\"dwn_href_tools\" href=\"javascript:openDownloadTools('" + jsonobj[1].EULAid + "','" + jsonobj[1].id + "',1,'" + jsonobj[1].platform + "')\" class=\"about_link\"><img src=\"../../Content/images/downloadforphone.png\" style=\"padding:0px 20px 0px 0px;\" border=\"0\" /></a></p>";
                    // }
                    //alert(innerHtml);

                    //innerHtml += "<a href=\"javascript:openDownloadTools('"+ jsonobj[key].link + "','"+ jsonobj[key].EULAid + "','" + jsonobj[key].id + "',1,'" + jsonobj[key].platform + "')\" class=\"about_link\"><img src=\"Images/downloadbtn.jpg\" border=\"0\" /></a>";
                    innerHtml += "</td><td valign=\"top\" align=\"left\"><p class=\"about2\" style=\"margin-top: 0px; text-align:justify;\">" + jsonobj[key].description + "</p></td>";
                    innerHtml += "</tr>";
                    innerHtml += "</table>";
                    innerHtml += "<p class=\"text13\">&nbsp;</p></td>";
                    innerHtml += "</tr>";

                    tools_number++;
                    //  alert(innerHtml);
                }
                innerHtml += "</table>";
                // $("#toolsDiv").empty();
                // alert(innerHtml);
                $("#toolsDiv").html(innerHtml);
            }
        }
    });
}

function upgrade() {
    if ($.trim($("#upgrade_fname").val()).length == 0) {
        $("#upgradeError").attr("innerHTML", "Please fill your first name!");
        return;
    }

    if ($.trim($("#upgrade_lname").val()).length == 0) {
        $("#upgradeError").attr("innerHTML", "Please fill your last name!");
        return;
    }

    if ($("#upgrade_country").val() == "0") {
        $("#upgradeError").attr("innerHTML", "Please select your country!");
        return;
    }

    if ($.trim($("#upgrade_coun").val()).length == 0 || $.trim($("#upgrade_area").val()).length == 0 || $.trim($("#upgrade_phone").val()).length == 0) {
        $("#upgradeError").attr("innerHTML", "Please fill your phone number!");
        return;
    }

    $.ajax({
        url: "/Handle/iniSession",
        type: "POST",
        async: false,
        data: ({
            act: "iniSession"
        }),
        success: function (data) {
            $.ajax({
                url: serverpath+'/getUserProfileByUserName',
                type: "POST",
                data: ({
                    action: "getUserProfileByUserName",
                    username: data
                }),
                datatype: "JSON",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        var jsonobj = data.result;

                        var userid = jsonobj[0].user_id;
                        var firstname = $("#upgrade_fname").val();
                        var lastname = $("#upgrade_lname").val();
                        var nickname = jsonobj[0].email;
                        var email = jsonobj[0].email;
                        var company = jsonobj[0].company;
                        var address = jsonobj[0].address;
                        var postcode = jsonobj[0].postcode;
                        var phonenumber = $("#upgrade_coun").val() + "-" + $("#upgrade_area").val() + "-" + $("#upgrade_phone").val();
                        var paypadid = jsonobj[0].paypad_id;
                        var area = jsonobj[0].area;
                        var sex = jsonobj[0].gender;
                        var ddegree = jsonobj[0].ddegree;
                        var mdegree = 2;
                        var picture = jsonobj[0].picture;
                        var country = $("#upgrade_country :selected").val();
                        var timezone = "";
                        //var timezone = $("#upgrade_country :selected").attr("item");
                        var website = jsonobj[0].website;
                        var bankname = jsonobj[0].bankname;
                        var billaccount = jsonobj[0].billaccount;
                        var bankaba = jsonobj[0].bankABA;
                        var bankswift = jsonobj[0].bankSWIFT;
                        var notice1 = jsonobj[0].notice1;
                        var notice2 = jsonobj[0].notice2;
                        var status = jsonobj[0].status;
                        var paymenttype = jsonobj[0].paymenttype;

                        $.ajax({
                            url: serverpath+'/setUserProfile',
                            type: "POST",
                            data: ({
                                action: "setUserProfile",
                                userid: userid,
                                email: email,
                                firstname: firstname,
                                lastname: lastname,
                                nickname: nickname,
                                company: company,
                                phone: phonenumber,
                                timezone: timezone,
                                postcode: postcode,
                                country: country,
                                website: website,
                                bankname: bankname,
                                billaccount: billaccount,
                                notice1: notice1,
                                notice2: notice2,
                                status: status,
                                ddegree: ddegree,
                                mdegree: mdegree,
                                address: address,
                                paypadid: paypadid,
                                area: area,
                                sex: sex,
                                picture: picture,
                                bankaba: bankaba,
                                bankswift: bankswift,
                                paymenttype: paymenttype
                            }),
                            datatype: "JSON",
                            async: false,
                            success: function (data) {
                                if (data.status == "success") {
                                    $("#upgradeResult").attr("innerHTML", "Congratulations, you can download paid apps now!!");
                                    $("#upgrade_result_table").css("display", "block");
                                    $("#upgrade_table").css("display", "none");

                                } else {
                                    $("#upgradeError").attr("innerHTML", "Fail to upgrade your account, please try again later!");
                                }
                            }
                        });
                    }
                }
            });
        }
    });
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function openUtilityDialog() {
    $.post(serverpath+"/DownloadUtility", function (data) {
        window.location = "#";
        $("body").append(data);
        $("body").css("overflow", "hidden");

        // Get the A tag
        var id = "#qrcode_dialog";

        // Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        // Set height and width to mask to fill up the whole screen
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });

        // transition effect
        $('#mask').fadeIn(700);
        $('#mask').fadeTo(700, 0.8);

        // Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // Set the popup window to center
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        // transition effect
        $(id).fadeIn(700);
    });
}
