﻿var objSite = new Object();
if (window.location.href.indexOf("expenio.com") != -1) {
    objSite.Base = "http://www.expenio.com/";
} else {
    objSite.Base = "";
}
objSite.Blogging = objSite.Base + 'Blogging.aspx';
objSite.HomePage = objSite.Base+'default.aspx';
objSite.HowPage = objSite.Base + 'how.aspx';
objSite.PrivacyPage = objSite.Base + 'privacy.aspx';
objSite.ContactPage = objSite.Base + 'contact.aspx';
objSite.SettingPage = objSite.Base + 'Manage.aspx';
objSite.MessagePage = objSite.Base + 'Messaging.aspx';
objSite.Views = objSite.Base + 'managementview.aspx';
objSite.ReportsPage = objSite.Base + 'reports.aspx';
objSite.Payments = objSite.Base + 'payments.aspx';
objSite.Photos = objSite.Base + 'photos.aspx';
objSite.PhotosPage = function () {
    window.location = objSite.Photos;
}
objSite.Reports = function () {
    window.location = objSite.ReportsPage;
};

objSite.Messages = function() {
    window.location = objSite.MessagePage;
};
objSite.GoToBilling = function () {
    window.location = objSite.Payments;
}
objSite.SearchPage = objSite.Base + 'search.aspx';
objSite.UserPage = objSite.Base + 'User.aspx';
objSite.UserInfoPage = function() {
    window.location = objSite.UserPage;
};

objSite.RegistrationPage = objSite.Base + 'registration.aspx';
objSite.ResourcePage = 'Resources.aspx';
objSite.Home = function() {
    window.location = this.HomePage;
};
objSite.How = function() {
window.location = this.HowPage;
};
objSite.BlogMe = function() {
    window.location = this.Blogging;
};
objSite.GoToSettings = function() {
 window.location = objSite.SettingPage;
};
objSite.Privacy = function() {
window.location = this.PrivacyPage;
};
objSite.Contact = function() {
window.location = this.ContactPage;
};

objSite.Resources = function() {
window.location = this.ResourcePage;
};

objSite.dir = "0";  
objSite.delay = "1";

objSite.BlogTextUpdated = function(e) {
    alert(e);
}

objSite.GeneralSettings = function(){
    window.location = objSite.SettingPage;
}
objSite.PopulateBlogEntry = function(ftbname) {
    objSite.RichTextArea = ftbname;
    Application.Web.Proxy.Blog_Get(objSite.BlogId, function(e) {

        document.getElementById("title").value = e.Subject;
        document.getElementById(objSite.RichTextArea).innerText = e.Body;
        objSite.RichTextArea = undefined;

    }, function(e) { alert('Could not update entry. Please try again: ' + e); });

}

objSite.Cart_Add = function (id) {
    if (objSite.CurrentResourceId == undefined) {
        alert('Please wait and try again shortly.');
        return;
    }
    Application.Web.Proxy.Cart_AddItem(objSite.CurrentResourceId, function (e) {

        document.getElementById("MyCartCount").innerHTML = e.toString();

    }, function (e) { alert('Could not add entry. Please try again'); });


}

objSite.BlogAdd = function(form, ftbname) {

    var subject = form.title.value == undefined ? 'Untitled entry' : form.title.value;
  
    var body = document.getElementById(ftbname).innerText;

    Application.Web.Proxy.Blog_Add((objSite.BlogId == undefined? '':objSite.BlogId), subject, body, function(e) {

        window.location = objSite.Blogging;

    }, function(e) { alert('Could not add entry. Please try again: ' + e); });
}
objSite.GetUserResourcesHTML = function() {



    Application.Web.Proxy.User_GetMedia(function(e) {


        document.getElementById('UserMedia').innerHTML = e.HTML;
    }, function(e) { });
    //document.location = 'Resources.aspx';


}
window.GetUserResourcesHTML = objSite.GetUserResourcesHTML;
objSite.AddResourceSuccess = function() {
    objSite.IsBusy(true, 'Successfully added resource', function() { objSite.IsBusy(false); objSite.GetUserResourcesHTML(); }, true);

}

objSite.AddResourceFail = function(e) {
    objSite.IsBusy(true, 'Could not add resource. Please contact support@expenio.com with error code SERVFAIL_ADDRES_01', function() { objSite.IsBusy(false); }, true);
}


objSite.EditResource = function(id) {
    window.location = 'Manage/EditResource.aspx?id=' + id;
}

objSite.AddResource = function(form) {


    if (objSite.View == "book") {




        Application.Web.Proxy.Resource_Uploaded(objSite.UploadToken, function(e) {

            if (e != true) {

                alert('You have not uploaded any content. Please upload some content before continuing.');

            } else {
                objSite.IsBusy(true, 'Adding resource. Please wait...', function() { }, false);
                Application.Web.Proxy.Resource_AddBook(form.title.value, form.series.value, form.author.value, form.publisher.value, form.summary.value, form.publicationdate.value, form.isbn.value, form.price.value, function(e) {

                    objSite.AddResourceSuccess();

                }, function(e) { })

            }



        }, function(e) { objSite.AddResourceFail(e); })







    }
    if (objSite.View == "audio") {


        Application.Web.Proxy.Resource_Uploaded(objSite.UploadToken, function(e) {

            if (e != true) {

                alert('You have not uploaded any content. Please upload some content before continuing.');

            } else {

                objSite.IsBusy(true, 'Adding resource. Please wait.', function() { }, false);
                Application.Web.Proxy.Resource_AddAudio(form.asummary.value, form.atitle.value, form.acomposer.value, form.aartist.value, form.aclassification.value, form.aminage.value, form.aurl.value, form.aprice.value, function(e) {

                    objSite.AddResourceSuccess();

                }, function(e) { objSite.AddResourceFail(e); }

                );



            }



        }, function(e) { alert('Search failed ' + e); })



    }
    if (objSite.View == "video") {




        Application.Web.Proxy.Resource_Uploaded(objSite.UploadToken, function(e) {

            if (e != true) {

                alert('You have not uploaded any content. Are you sure you wish to continue?');

            } else {

                objSite.IsBusy(true, 'Adding resource. Please wait.', function() { }, false);
                Application.Web.Proxy.Resource_AddVideo(form.vsummary.value, form.vtitle.value, form.vdirector.value, form.vproducer.value, form.vminage.value, form.vurl.value, form.vprice.value, function(e) {

                    objSite.AddResourceSuccess();

                }, function(e) { objSite.AddResourceFail(e); }

                );



            }



        }, function(e) { alert('Search failed ' + e); })



    }
    if (objSite.View == "software") {

    }
}

var isDOM = document.getElementById ? 1 : 0;
var isIE = document.all ? 1 : 0;
objSite.showWin = function() {
    if (isDOM) { document.getElementById("popup").style.display = ""; }
    else if (isIE) { popup.style.display = ""; }
    document.getElementById("popup").style.visibility = "visible";
}
objSite.closeSearch = function() {
    if (isDOM) { document.getElementById("popup").style.display = "none" }
    else if (isIE) { popup.style.display = "none"; }
    document.getElementById("popup").style.visibility = "hidden";
    document.getElementById("loc").style.left = "1";
    document.getElementById("loc").style.top = "-600";

    for (var index = 0; index < 9; index++) {
        try{
        var element = document.getElementById("searchItem" + index);
     
        element.style.visibility = 'hidden';
        }catch(e){}
    }
}
objSite.SaveComment = function () {
    var txtComment = document.getElementById("txtComment").value;
    //alert('Save comment ' + txtComment + ' for resource ' + objSite.CurrentCommentingId);

    Application.Web.Proxy.Resource_AddComment(objSite.CurrentCommentingId, objSite.LoggedInUser.Id, txtComment, function () {
        var element = document.getElementById("WritableComment");

        element.style.visibility = 'hidden';
        var objCommentsArea = document.getElementById("mediaComments");
        objCommentsArea.innerHTML = objCommentsArea.innerHTML + "You just posted  a comment<br/>" + document.getElementById("txtComment").value;
    }, function () {
        alert('There was a problem adding a comment for this resource.');
    });

} 
objSite.WriteComment = function (id) {
    objSite.CurrentCommentingId = id;
    var element = document.getElementById("WritableComment");

    element.style.visibility = 'visible';

}
objSite.Out = function(item) {
    if (item.src.indexOf(objSite.View) != -1) {
        return;
    }
    item.style.opacity = "0.4";
    item.style.filter = "alpha(opacity = 40)";
}
objSite.Over = function(item) {
item.style.opacity = "0.9";
item.style.filter = "alpha(opacity = 90)";
}
objSite.ShowResults = function(dir) {
    var loc = document.getElementById("loc");

    if (objSite.dir == "1" && loc.style.pixelLeft < (screen.width - 1000) / 2) {
        loc.style.pixelLeft += 5;
        move = setTimeout("objSite.ShowResults(objSite.dir)", 0.1);
    }
    if (objSite.dir == "0" && loc.style.pixelTop < (screen.height - 1000) / 2) {
        loc.style.pixelTop += 5;
        move = setTimeout("objSite.ShowResults(objSite.dir)", 0.1);
    } else {
        setTimeout(function() {
            objSite.LoadItem(0);
        }, 500);

    }
}
objSite.ShowResource = function(ResourceItem) {

    if (ResourceItem.id.indexOf("searchItem") != -1) {
        var index = ResourceItem.id.substr(ResourceItem.id.indexOf("searchItem") + 10);
        
        window.location = 'view.aspx?id=' + objSite.SearchItemCollection[parseInt(index)].Id;
    }
}
objSite.GetPage = function() {

}
objSite.CloseUploader = function() {
    document.getElementById("uploader").src = 'blank.aspx';
    document.getElementById("UploadScreen").style.visibility = "hidden";
}

objSite.ShowUploader = function(token) {
    document.getElementById("uploader").src = 'uploader.aspx?upload_token=' + token + '&' + objSite.View + '=true';
    document.getElementById("UploadScreen").style.visibility = "visible";

    //window.open('uploader.aspx?upload_token=' + token + '&' + objSite.View + '=true', 'mywindow', 'width=800,height=700');
}

objSite.CloseCMS = function(){
document.getElementById("cms").src = 'blank.aspx';
document.getElementById("CMSScreen").style.visibility = "hidden";
}


objSite.LaunchBorrowerView = function (fragment) {

    document.getElementById("cms").src = objSite.Views + "?prepare=true&mode=users";
    document.getElementById("CMSScreen").style.visibility = "visible";

}

objSite.LaunchResourceView = function (fragment) {

    document.getElementById("cms").src = objSite.Views + "?prepare=true&mode=resources";
    document.getElementById("CMSScreen").style.visibility = "visible";

}
objSite.LaunchPurchaserView = function (fragment) {

    document.getElementById("cms").src = objSite.Views + "?prepare=true&mode=purchases";
    document.getElementById("CMSScreen").style.visibility = "visible";

}
objSite.LaunchCMS = function(fragment) {

document.getElementById("cms").src = 'cms.aspx?token=' + escape(fragment);
document.getElementById("CMSScreen").style.visibility = "visible";

}
objSite.SearchItemCollection = new Array();
objSite.LoadItem = function(index) {
    var searchItem = objSite.SearchResults[index];
    //alert(objSite.SearchResults.length);
    if (searchItem != undefined) {
        var element = document.getElementById("searchItem" + index);
        objSite.SearchItemCollection[index] = searchItem;
        if (element != undefined) {

            var desc = document.getElementById("description" + index);
            var icon = document.getElementById("icon" + index);
            var picture = document.getElementById("picture" + index);

            if (searchItem.Type == 'book') {
                icon.src = 'Images/book.png';
            }
            if (searchItem.Type == 'audio') {
                icon.src = 'Images/music.png';
            }

            if (searchItem.Type == 'film') {
                icon.src = 'Images/video.png';
            }
            if (searchItem.Type == 'picture') {
                icon.src = 'Images/picture.png';
            }

            desc.innerHTML = searchItem.Name;
            picture.src = searchItem.PreviewUrl;
            element.style.visibility = "visible";
            if (index < 10) {
                setTimeout("objSite.LoadItem(" + (index + 1) + ")", 0.1);
            }
        }
    }
}
objSite.Search = function(search, page, count) {

    document.location = objSite.SearchPage +'?query=' + search;
    return;
    objSite.LastSearch = search;

    Application.Web.Proxy.Search(search, page == undefined ? 1 : page, count == undefined ? 20 : count, function(e) {
        objSite.SearchResults = e.Results;
        if (e.Count == 0) {
            alert("There was no results found for '" + objSite.LastSearch + "'");
            return;
        }
        objSite.SearchItemCollection = new Array();
        objSite.showWin();
        objSite.ShowResults(objSite.dir);
        document.getElementById("SearchResultCount").innerHTML = e.Count + " search results for '" + objSite.LastSearch + "'";



    }, function(e) { alert('Search failed ' + e); })
}
objSite.IsBusy = false;

objSite.Registration = function(form) {
    if (objSite.IsBusy == true) {
        return;
    }
    objSite.IsBusy = true;
    if (form.type.selectedIndex == 0) {

        Application.Web.Proxy.RegisterUser(form.username.value, form.password.value, form.tel.value, form.firstname.value, form.lastname.value, form.address.value, form.city.value, form.town.value, form.postcode.value, form.country[form.country.selectedIndex].value, form.email.value, function(e) {
            objSite.IsBusy = false;
            var result = eval('(' + e + ')');
            if (result == true) {
                alert('Congratulations. You have successfully signed up. Please check your email inbox for confirmation email.');
                window.location = objSite.HomePage;
            } else {
                alert('Could not register. Please check your details');
            }

        }, function() {
        objSite.IsBusy = false;
        alert('Could not register. Please check your details');
        });
    } else {

        Application.Web.Proxy.RegisterContentProvider(form.username.value, form.password.value, form.tel.value, form.firstname.value, form.lastname.value, form.address.value, form.city.value, form.town.value, form.postcode.value, form.country[form.country.selectedIndex].value, form.email.value, form.companyname.value, form.companyaddress.value, form.companytown.value, form.companycity.value, form.companypostcode.value, form.companycountry[form.companycountry.selectedIndex].value, form.companytel.value, form.companyfax.value, form.companyemail.value, function(e) {
            var result = eval('(' + e + ')');
            if (result == true) {
                alert('Congratulations. You have successfully signed up. Please check your email inbox for confirmation email.');
                window.location = objSite.HomePage;
            } else {
                alert('Could not register. Please check your details');
            }

        }, function() {
            alert('Could not register. Please check your details');
        });


    }
};

objSite.Register = function() {
window.location = this.RegistrationPage;
};
objSite.GettingUserMeta = false;
objSite.UserAvailable = function(name, imageHolder, dialog) {
    if (name.value == '') {
        imageHolder.style.visibility = 'hidden';
    }

    objSite.GettingUserMeta = true;
    Application.Web.Proxy.UserNameAvailable(name.value, function(e) {
        objSite.GettingUserMeta = false;
        if (e == false) {
            imageHolder.style.visibility = 'visible';
            imageHolder.src = 'Images/cross.png';
            if (dialog) {
                alert('The username ' + name.value + ' is already registered. Please choose a different username.');
                name.value = '';
                name.focus();
                
            }
        } else {
            imageHolder.style.visibility = 'visible';
            imageHolder.src = 'Images/tick.png';
        }
    }, function() {

        alert('Failed during UsernameAvailable call. Please try again');
    });
};



objSite.GetLoggedInUser = function() {

    Application.Web.Proxy.GetLoggedInUser(function(e) {

        var result = e;

        objSite.LoggedInUser = result;
        document.getElementById('LoggedIn').innerHTML = '<img src="Images/loggedin.png" height="16px" width="16px"/><a href="myaccount.aspx">' + objSite.LoggedInUser.name + ' logged in with (' + objSite.LoggedInUser.messages + ') messages</a>  | <a href="javascript:objSite.Logout();">Logout</a>';
        document.getElementById('LoggedIn').style.visibility = 'visible';
        document.getElementById('LoggingInForm').style.visibility = 'hidden';

        setInterval('Application.Web.Proxy.Ping(function() { }, function() { });', 60000);
   
        
    }, function() {

        alert('Failed during GetUser call. Please try again');
    });
};



objSite.LoggedInUser = undefined;

objSite.GetNewUsers = function() {

    Application.Web.Proxy.GetNewUsers(function(e) {

        var newUserArea = document.getElementById("newUsers");
        var users = '';
        for (var x = 0; x < e.length; x++) {
            users = users + '<a href="' + e[x] + '/default.aspx">' + e[x] + '</a>';
        }
        newUserArea.innerHTML = users;
    }, function() { alert('There was a problem getting new users.'); });

}


objSite.Logout = function() {

    Application.Web.Proxy.Logout( function(e) {
    window.location = objSite.HomePage;
   }, function(){alert('There was a problem logging out.');}); 
   
}

objSite.Login = function(form, user, pass) {
    
    objSite.LogginForm = form;
    Application.Web.Proxy.Authenticate(user, pass, function(e) {
        var result = eval('(' + e + ')');
        if (result == true) {
            window.location = objSite.HomePage + '?loggedin=true';
        } else {
            objSite.LogginForm.UserName.value = '';
            objSite.LogginForm.Password.value = '';
            objSite.LogginForm.UserName.focus();
            alert('Invalid username or password. Please try again.');
        }

    }, function() {

        alert('Failed during login call. Please try again');
    });
};
objSite.Loaded = function() {
    if (window.location.href.indexOf('loggedin=true') != -1) {
        this.GetLoggedInUser();
    }
    try {
        if (objSite.OnCompleted != undefined) {
            objSite.OnCompleted();
        }
    } catch (e) { }
};



objSite.CheckEmail = function(formInput) {
    if (typeof (formInput) != "object") {
        alert("Validation not supported on this browser.");
        return (false);
    }
    if (checkValid == undefined) {
        function checkValid(formField) {
            if (checkValidation(formField) == true) {
                alert('E-Mail Address Validates OK');
            }

            return (false);
        }

        function stringEmpty(formField) {
            // CHECK THAT THE STRING IS NOT EMPTY
            if (formField.length < 1) {
                return (true);
            } else {
                return (false);
            }
        }

        function noAtSign(formField) {
            // CHECK THAT THERE IS AN '@' CHARACTER IN THE STRING
            if (formField.indexOf('@', 0) == -1) {
                return (true)
            } else {
                return (false);
            }
        }

        function nothingBeforeAt(formField) {
            // CHECK THERE IS AT LEAST ONE CHARACTER BEFORE THE '@' CHARACTER
            if (formField.indexOf('@', 0) < 1) {
                return (true)
            } else {
                return (false);
            }
        }

        function noLeftBracket(formField) {
            // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR LEFT BRACKET
            if (formField.indexOf('[', 0) == -1 && formField.charAt(formField.length - 1) == ']') {
                return (true)
            } else {
                return (false);
            }
        }

        function noRightBracket(formField) {
            // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR RIGHT BRACKET
            if (formField.indexOf('[', 0) > -1 && formField.charAt(formField.length - 1) != ']') {
                return (true);
            } else {
                return (false);
            }
        }

        function noValidPeriod(formField) {
            // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
            if (formField.indexOf('@', 0) > 1 && formField.charAt(formField.length - 1) == ']')
                return (false);

            // CHECK THAT THERE IS AT LEAST ONE PERIOD IN THE STRING
            if (formField.indexOf('.', 0) == -1)
                return (true);

            return (false);
        }

        function noValidSuffix(formField) {
            // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
            if (formField.indexOf('@', 0) > 1 && formField.charAt(formField.length - 1) == ']') {
                return (false);
            }

            // CHECK THAT THERE IS A TWO OR THREE CHARACTER SUFFIX AFTER THE LAST PERIOD
            var len = formField.length;
            var pos = formField.lastIndexOf('.', len - 1) + 1;
            if ((len - pos) < 2 || (len - pos) > 4) {
                return (true);
            } else {
                return (false);
            }
        }
    }

    var message;

    if (stringEmpty(formInput.value)) {
        //message = "Error! There is no input value entered.";
        //alert(message);
    } else if (noAtSign(formInput.value)) {
        message = "Error! The address \"" + formInput.value + "\" does not contain an '@' character.";
        alert(message);
    } else if (nothingBeforeAt(formInput.value)) {
        message = "Error! The address \"" + formInput.value;
        message += "\" must contain at least one character before the '@' character";
        alert(message);
    } else if (noLeftBracket(formInput.value)) {
        message = "Error! The address \"" + formInput.value;
        message += "\" contains a right square bracket ']',\nbut no corresponding left square bracket '['.";
        alert(message);
    } else if (noRightBracket(formInput.value)) {
        message = "Error! The address \"" + formInput.value;
        message += "\" contains a left square bracket '[',\nbut no corresponding right square bracket ']'.";
        alert(message);
    } else if (noValidPeriod(formInput.value)) {
        message = "Error! The address \"" + formInput.value + "\" must contain a period ('.') character.";
        alert(message);
    } else if (noValidSuffix(formInput.value)) {
        message = "Error! The address \"" + formInput.value;
        message += "\" must contain a two, three or four character suffix.";
        alert(message);
    } else {
        message = "Success! The email address \"" + formInput.value + "\" validates OK.";
        return;
    }

    var objType = typeof (formInput.focus);
    if (objType == "object" || objType == "function") {
        formInput.focus();
    }
}




objSite.CheckPassword = function(pass, imageHolder, alertallowed) {
    if (objSite.GettingUserMeta) {
        return;
    }
    if (pass.valueOf == '') {
        imageHolder.style.visibility = 'hidden';
    }

    var lowercaseletter = /[a-z]/.test(pass.value);
    var uppercaseletter = /[A-Z]/.test(pass.value);
    var digit = /\d/.test(pass.value);

    var low_security = lowercaseletter || uppercaseletter || digit;
    var med_security = (lowercaseletter && uppercaseletter) || (lowercaseletter && digit) || (digit && uppercaseletter);
    var high_security = lowercaseletter && uppercaseletter && digit;
    var hasMatch = high_security && pass.value.length >= 6;




    if (hasMatch == false) {
        if (alertallowed) {
            pass.value = '';
            alert('Your password needs to be a minimum of 6 characters, containing 1 uppercase and 1 alpha-numerical character. Please try again.');
        }
        pass.focus();
        imageHolder.style.visibility = 'visible';
        imageHolder.src = 'Images/cross.png';
    }
    else {
        imageHolder.style.visibility = 'visible';
        imageHolder.src = 'Images/tick.png';
    }
}
objSite.RegistrationTypeChanged = function(dropdown, contentArea, IsInverse) {
    if (IsInverse == undefined) {
        IsInverse = false;
    } else {
        IsInverse = true;
    }

    if (dropdown.selectedIndex == 0) {
        contentArea.style.visibility =(IsInverse == true? 'visible': 'hidden');
    }
    if (dropdown.selectedIndex == 1) {
        contentArea.style.visibility =(IsInverse == true? 'hidden': 'visible');
    }
}

document.objSite = objSite;




























