﻿var perpage = 6;
var galleryperpage = 12;
var currentpage = 0;
var total = 0;
var pagecount = 0;

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        var value = $.getUrlVars()[name];
        return value.replace(/#/g, "");
    }
});

function include(div, filename) {
    $('#'+div).load(filename, function (response, status, xhr) {
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            //alert(msg + xhr.status + " " + xhr.statusText);
            $("#error").html(msg + xhr.status + " " + xhr.statusText);
        }
    });
}

function onBluremailtextguide(textbox, textguide) {
    var email = textbox.value;
    if (email.trim().length == 0)
        textbox.value = textguide;
    else if (emailvalidation(textbox) == false) {
        //alert('Email Address incorrect format.');
        textbox.value = textguide;
    }
}

function onFocusmailtextguide(textbox) {
    if(emailvalidation(textbox) == false)
        textbox.value = "";
}

function emailvalidation(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = email.value;
    if (reg.test(address) == false) {
        return false;
    }
}

function submitEmail(textbox) {
    if (emailvalidation(textbox) == false) {
        if (isProfileExist()) {
            var profile = getProfile();
            var lang = profile.language;
            if (lang == "th-TH")
                alert('กรุณากรอก Email ที่ถูกต้อง');
            else
                alert('Please use valid email address.');
        } else {
            alert('Please use valid email address.');
        }
    } else {
        addEmailSubscription(textbox);
    }
}

function addEmailSubscription(email) {
    var isCompleted = false;
    var emailaddress = email.value != undefined || email.value != null ? email.value : "";
    if (emailaddress.length > 0) {
        var jqxhr = $.post("emailsubscription.php?action=subscription&val=" + emailaddress, function () {
            //alert("success");
        })
        .success(function (msg) {
            $("#messagebox").append(msg);
            isCompleted = true;
            if (isProfileExist()) {
                var profile = getProfile();
                var lang = profile.language;
                if (lang == "th-TH")
                    alert('บันทึก Email เสร็จเรียบร้อย');
                else
                    alert('Your E-mail already saved.');
            } else {
                alert('Your E-mail already saved.');
            }

        })
        .error(function (x, e) {
            if (x.status == 0) {
                $("#messagebox").html('You are offline!!\n Please Check Your Network.');
                //alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                $("#messagebox").html('Requested URL not found.');
                //alert('Requested URL not found.');
            } else if (x.status == 500) {
                $("#messagebox").html('Internel Server Error.');
                //alert('Internel Server Error.');
            } else if (e == 'parsererror') {
                $("#messagebox").html('Error.\nParsing JSON Request failed.');
                //alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                $("#messagebox").html('Request Time out.');
                //alert('Request Time out.');
            } else {
                $("#messagebox").html('Unknow Error.\n' + x.responseText);
                //alert('Unknow Error.\n'+x.responseText);
            }
        })
        .complete(function () { });
    }
    return isCompleted;
}

//-------------------------------------------------------------load event and gallery------------------------------------------------------------------------

function loagEventGallery(current, typename , btnPrevious, btnNext) {
    var profile = getProfile();
    if (isProfileExist()) {
        var datafile = "XML/" + typename + "/" + profile.language + "/data.xml";
        $.ajax({
            type: "GET",
            url: datafile,
            dataType: "xml",
            success: function (xml) {
                $(xml).find('images').each(function () {
                    $('#pagePanel').html("");
                    total = $(this).find('gallery').length;
                    pagecount = Math.ceil(total / perpage);
                    currentpage = current;
                    renderEventGallery(this, current, typename);

                    //set show and hid button
                    var btn_previous = $('#' + btnPrevious);
                    var btn_next = $('#' + btnNext);
                    if (currentpage == 0) btn_previous.hide(); else btn_previous.show();
                    if ((currentpage+1) == pagecount) btn_next.hide(); else btn_next.show();
                });
            }
        });
    }
}

function renderEventGallery(gallery, currentpage, typename) {
    var rowcount = 0;
    var fromRecord = currentpage * perpage;
    var toRecord = fromRecord + perpage;
    var layout = "";
    $('#panel').html("");
    $(gallery).find('gallery').slice(fromRecord, toRecord).each(function () {
        rowcount++;
        var isNewRow = rowcount % 3;
        var id = $(this).attr('id');
        var gname = $(this).attr('name');
        var path = $(this).attr('path');
        var title = $(this).attr('title');
        var header = $(this).attr('header');
        var date = $(this).attr('date');
        var location = $(this).attr('location');
        var facebook = $(this).attr('facebook');
        var length = $(this).find('photo').length;
        if (length > 0) {
            var number = $.random(length);
            var ranimage = $(this).find('photo').get(number);
            var url = $(ranimage).find('url').text();
            var name = $(ranimage).find('name').text();
            var desc = $(ranimage).find('desc').text();

            //alert(typename);
            if (typename == "events")
                layout += layoutEvent(isNewRow, gname, title, name, url, desc, date, location, facebook, rowcount);
            else if (typename == "gallery")
                layout += layoutGallery(isNewRow, gname, title, name, url, desc, date, location, rowcount);
        }
    });

    layout = "<ul><li>" + layout + "</li></ul>";
    if (layout != null && layout != undefined) {
        $('#panel').append(layout);
    }
}

function layoutEvent(isNewRow, galleryname, title, name, url, desc, date, location, facebook, id) {
    var imageUrl = galleryname + "/" + url;
    var link = "activities_inner.html?gal=" + galleryname;
    var layout = "<ul><li>" +
                    "<div><a href='" + link + "'><img src='images/gallery/" + imageUrl + "' width='315' height='200' /></a></div>" +
                    "<div class='info_album info_event'>" +
                    "<p><a href='" + link + "' class='title_album'>" + title + "</a></p>" +
                    "<p class='date_update'>" + date + "</p>" +
                    "</div>" +
                    "<div class='likesocial'>" +
                        "<div class='info_envent'>" +
                            "<p>" + desc + "</span>" +
                            "<a href='" + link + "' class='btn_viewmoreevent'><span>view more</span></a>" +
                        "</div>" +
                        "<div class='nuberlikesocial'>" +
                            //"<img src='images/gallery/piclike.jpg' width='141' height='20' />" +
                            loadEventGallerySocialNetWork(id,link) +
                        "</div>" +
                    "</div>" +
                "</li></ul>";
    return layout; //isNewRow == 0 ? "<ul><li><ul>" + layout + "</ul></li></ul>" : layout;
}

function layoutGallery(isNewRow, galleryname, title, name, url, desc, date, location, id) {
    var imageUrl = galleryname + "/" + url;
    var link = "gallery_inner.html?gal=" + galleryname;
    var layout = "<ul><li>" +
                    "<div><a href='" + link + "'><img src='images/gallery/" + imageUrl + "' width='315' height='180' /></a></div>" +
                    "<div class='info_album info_gallery'>" +
                    "<p><a href='" + link + "' class='title_album'>" + title + "</a></p>" +
                    "<p class='date_update'>" + date + "</p>" +
                    "</div>" +
                    "<div class='likesocial'>" +
                        //"<img src='images/gallery/piclike.jpg' width='141' height='20' />"+
                        loadEventGallerySocialNetWork(id,link) +
                    "</div>" +
                "</li></ul>";
    return layout;// isNewRow == 0 ? "<ul><li><ul>" + layout + "</ul></li></ul>" : layout;
}

//-----------------------------------------------------------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------load event detail-----------------------------------------------------------------

function loadEventDetail(eventtitle, eventname, eventposted, eventcontent, btnprevious, btnnext, btnmore, imagepanel) {
    if (isProfileExist()) {
        var profile = getProfile();
        var event = $.getUrlVar('gal');
        var datafile = "XML/events/" + profile.language + "/data.xml";
        var imageLimit = 9;
        var currentRecord = 0;
        var recordNumber = 0;
        var recordArray = new Array();
        $.ajax({
            type: "GET",
            url: datafile,
            dataType: "xml",
            success: function (xml) {
                $(xml).find('images').each(function () {
                    $(this).find('gallery').each(function () {
                        var id = $(this).attr('id');
                        var gname = $(this).attr('name');
                        var title = $(this).attr('title');
                        var facebook = $(this).attr('facebook');
                        var youtube = $(this).attr('youtube');
                        recordArray[recordNumber] = gname;
                        recordNumber++;

                        if (event == gname) {
                            currentRecord = recordNumber - 1;
                            $(this).find('photo').each(function () {
                                var url = $(this).find('url').text();
                                var name = $(this).find('name').text();
                                var galleryname = $(this).find('galleryname').text();
                                var posted = $(this).find('posted').text();
                                var contentlink = "html/events/" + profile.language + "/" + $(this).find('contentlink').text();
                                var desc = $(this).find('desc').text();

                                $('#' + eventtitle).html(title);
                                $('#' + eventname).html(name);
                                $('#' + eventposted).html(posted);
                                //$('#' + btnmore).attr('href', facebook);
                                $('#' + btnmore).attr('href', 'gallery_inner.html?gal=' + galleryname);
                                include(eventcontent, contentlink);
                                loadPreviewGallery(galleryname, imagepanel, imageLimit);
                                loadYoutube(youtube);
                            });
                        }
                    });
                });
                var previous = $('#' + btnprevious);
                var next = $('#' + btnnext);
                previous.attr('href', 'activities_inner.html?gal=' + recordArray[currentRecord - 1]);
                next.attr('href', 'activities_inner.html?gal=' + recordArray[currentRecord + 1]);

                if (currentRecord == 0) previous.hide(); else previous.show();
                if (currentRecord == (recordArray.length - 1)) next.hide(); else next.show();
            }
        });
    }
}

function loadPreviewGallery(galleryname, imagepanel, imageLimit) {
    if (isProfileExist()) {
        var imageCount = 0;
        var profile = getProfile();
        var datafile = 'XML/gallery/' + profile.language + '/data.xml';
        $.ajax({
            type: 'GET',
            url: datafile,
            dataType: 'xml',
            success: function (xml) {
                $(xml).find('images').each(function () {
                    $(this).find('gallery').each(function () {
                        var id = $(this).attr('id');
                        var gname = $(this).attr('name');
                        var type = $(this).attr('type');
                        var date = $(this).attr('date');
                        var location = $(this).attr('location');

                        if (gname == galleryname) {
                            var countPhoto = $(this).find('photo').length;
                            if (countPhoto > 0) {
                                $(this).find('photo').each(function () {
                                    var url = $(this).find('url').text();
                                    var name = $(this).find('name').text();
                                    var desc = $(this).find('desc').text();
                                    var layout = GalleryPreviewLayout(gname, name, url);

                                    if (imageCount == imageLimit) return;
                                    imageCount++;

                                    $('#' + imagepanel).append(layout);
                                    $('a[@rel*=lightbox]').lightBox();
                                });
                            } else {
                                $('#' + imagepanel).hide();
                            }
                        }
                    });
                });
                if (imageCount == 0) {$('#sidebargallery').hide(); } //hide sidebargallery
            }
        });
    }
}

function GalleryPreviewLayout(galleryname, name, url) {
    return "<li><a href='images/gallery/" + galleryname + "/" + url + "' rel='lightbox'><img src='images/gallery/" + galleryname + "/" + url + "' width='100' height='67' /></a></li>";
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------load gallery detail-----------------------------------------------------------------

function loagGallery(current, btnPrevious, btnNext, btnMore, gallerypath, galleryheader, galleryposted) {
    var profile = getProfile();
    var gallery = $.getUrlVar('gal');
    if (isProfileExist()) {
        var rowcount = 0;
        var datafile = "XML/gallery/" + profile.language + "/data.xml";
        $.ajax({
            type: "GET",
            url: datafile,
            dataType: "xml",
            success: function (xml) {
                $(xml).find('images').each(function () {
                    $(this).find("gallery[name='" + gallery + "']").each(function () {
                        var id = $(this).attr('id');
                        var gname = $(this).attr('name');
                        var path = $(this).attr('path');
                        var header = $(this).attr('header');
                        var posted = $(this).attr('posted');
                        var facebook = $(this).attr('facebook');

                        $('#gallery').html("");
                        total = $(this).find('photo').length;
                        pagecount = Math.ceil(total / galleryperpage);
                        currentpage = current;
                        renderGallery(this, gname, current);

                        $('#' + gallerypath).html(path);
                        $('#' + galleryheader).html(header);
                        $('#' + galleryposted).html(posted);


                        //set show and hid button
                        var btn_previous = $('#' + btnPrevious);
                        var btn_next = $('#' + btnNext);
                        var btn_more = $('#' + btnMore);

                        if (currentpage == 0) btn_previous.hide(); else btn_previous.show();
                        if ((currentpage + 1) == pagecount) btn_next.hide(); else btn_next.show();
                        btn_more.attr('href', facebook);
                    });
                });
            }
        });
    }
}

function renderGallery(photos, galleryname, currentpage) {
    var rowcount = 0;
    var fromRecord = currentpage * galleryperpage;
    var toRecord = fromRecord + galleryperpage;
    var layout = "";

    $(photos).find('photo').slice(fromRecord, toRecord).each(function () {
        rowcount++;
        var isNewRow = rowcount % 4;
        var url = $(this).find('url').text();
        var name = $(this).find('name').text();
        var desc = $(this).find('desc').text();

        layout += layoutPhoto(isNewRow, galleryname, name, url, desc);
    });

    layout = "<ul><li>" + layout + "</li></ul>";
    if (layout != null && layout != undefined) {
        $('#gallery').append(layout);
        $('a[@rel*=lightbox]').lightBox(); 
    }
}

function layoutPhoto(isNewRow, galleryname, name, url, desc) {
    var imageUrl = galleryname + "/" + url;
    var link = "gallery_inner.html?gal=" + galleryname;
    var layout = "<ul><li>" +
                    "<a href='images/gallery/" + imageUrl + "' rel='lightbox'><img src='images/gallery/" + imageUrl + "' width='233' height='155' /></a>" +
                "</li></ul>";
    return isNewRow == 0 ? "<ul><li><ul>" + layout + "</ul></li></ul>" : layout;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------load social network---------------------------------------------------------------------------
function loadAllSocialNetwork()
{ 
    return "<div>" +
        "<div style='float: left;'>" +
            "<!--Twitter -->" +
            "<a href='http://twitter.com/share' class='twitter-share-button'" +
                "data-count='horizontal' data-via='Your-Data' data-related='Data-Related:Data-Related-Description'>Tweet</a>" +
            "<script type='text/javascript' src='http://platform.twitter.com/widgets.js'></script>" +
            "<!--Google Plus -->" +
            "<div id='g-plusone'>" +
            "</div>" +
        "</div>" +
        "<div style='float: left;'>" +
            "<!--Facebook -->" +
            "<div id='fb-root'></div>" +
            "<script src='http://connect.facebook.net/en_US/all.js#xfbml=1'></script>" +
            "<fb:like href='' send='true' layout='button_count' width='50' show_faces='true' font=''></fb:like>" +
        "</div>" +
    "</div>" ;
}

function loadSocialNetwork() {
    var social = "<div>" +
        "<div style='float: left;'>" +
            "<div id='g-plusone'>" +
            "</div>" +
        "</div>" +
        "<div style='float: left;'>" +
            "<div id='fb-root'></div>" +
            "<fb:like href='' send='true' layout='button_count' width='50' show_faces='true' font=''></fb:like>" +
        "</div>" +
    "</div>";
    //alert(social);
    return social
}

function loadEventGallerySocialNetWork(id,url) {
    var sPath = window.location.href;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    var link = encodeURI(sPath.replace(sPage, '') + url);
    var facebooklink = link.replace(":", "%3A").replace("/", "%3F");
    var social = "<div>" +
    "<div id='like_" + id + "' class='facebook'></div>" +
    "<div id='plusone_" + id + "' class='google'></div>" +
    "<script type='text/javascript'>" +
        "$('#like_" + id + "').fbjlike({" +
            "href: '" + url + "'," +
            "layout: 'button_count'," +
            "showfaces: false," +
            "send: false," +
            "comments: false," +
            "buttonWidth: 80" +
        "});" +
        "$('#plusone_" + id + "').gplusone({" +
            "href: '" + url + "'," +
            "size: 'medium'" +
        "});" +
    "</script>" +
    "</div>";
    //alert(social);
    return social
}

function loadYoutube(url) {
    var youtube = "<object width='304' height='171'>" +
    "<param name='movie' value='" + url + "'</param>" +
    "<param name='allowFullScreen' value='true'></param>" +
    "<param name='allowScriptAccess' value='always'></param>" +
    "<embed src='" + url + "'" +
        "type='application/x-shockwave-flash'" +
        "allowfullscreen='true'" +
        "allowscriptaccess='always'" +
        "width='304' height='171'>" +
    "</embed>" +
    "</object>";
    if (url != undefined || url != null) {
        if (url.length > 0) $('#videoclipbox').html(youtube);
    }
    else {
        $('#vdo_chip_box').hide();
    }
}

//-----------------------------------------------------------------------------------------------------------------------------------------------------------
