var current_html_doc = window.location.href.split('?')[0];
var current_page = "";

// loading main xml (menu data, logo, contact info)
var jqxhr;
$(document).ready(function () {
    jqxhr = $.ajax({ url: "data/main.xml" })
                .success(function () { populatePage(); })
                .error(function () { alert("Could not load main data"); })
});

function populatePage() {
    var xmlDoc = jqxhr.responseXML.documentElement;

    // placing logo image
    placeLogoImg(xmlDoc);

    // place Contact Info
    placeContactInfo(xmlDoc);

    // place menu items
    placeMenuItems(xmlDoc);

    // load page content
    loadContent();

}

function getMovieNumById(movie_id) {
    var movie_num = false;
    for (var i = 0; i < movie_array.length; i++) {
        if (movie_array[i].id_ == movie_id) {
            movie_num = i;
            break;
        }
    }

    return movie_num;
}

function showVideo() {
    var video_num_to_show = 0;

    if (args_array['show_video']) {
        video_num_to_show = getMovieNumById(args_array['show_video']);
    }

    if (movie_array[video_num_to_show]) {

        document.getElementById('show_video_div').style.display = '';

        document.getElementById('video_div').innerHTML = movie_array[video_num_to_show].embed_code;

        var vid_title_span = document.createElement('span');
        vid_title_span.innerHTML = movie_array[video_num_to_show].title_ + '/';

        var vid_subtitle_span = document.createElement('span');
        vid_subtitle_span.className = 'video_subtitle_span';
        vid_subtitle_span.innerHTML = movie_array[video_num_to_show].subtitle_;

        document.getElementById('video_title_div').appendChild(vid_title_span);
        document.getElementById('video_title_div').appendChild(vid_subtitle_span);

        document.getElementById('video_details_div').innerHTML = movie_array[video_num_to_show].description_html;

        //showing more from...
        if (movie_array.length > 1) {
            document.getElementById('more_from_div').innerHTML = 'More from "' + menu_item_array[menu_item_currently_selected].text_ + '"';
            document.getElementById('more_from_div').style.display = 'block';
        }

        movie_shown = video_num_to_show;
    }
}

function loadContent() {
    var xml_folder = 'data/';

    if (menu_item_currently_selected) {
        current_page = menu_item_array[menu_item_currently_selected].page_;
    }
    else {
        current_page = menu_item_array[0].page_;
    }

    var request_doc = xml_folder + current_page + '.xml';
    jqxhr = $.ajax({ url: request_doc })
                .success(function () { populateContent(); })
                .error(function () { alert("Could not load page content"); })
}

var other_page_num = 0;

function addThumbsFromOtherPage() {
    other_page_num++;
    if(other_page_num < menu_item_array.length) { 

        /*********** NOT USED - NOT RANDOM *************
        var random_page_num = menu_item_currently_selected;
        while (other_page_num == menu_item_currently_selected)
            random_page_num = randomFromTo(0, (menu_item_array.length - 1));
        */

    // loading other page movie list
    var xml_folder = 'data/';

    var other_page = menu_item_array[other_page_num].page_;

    var request_doc = xml_folder + other_page + '.xml';
    jqxhr = $.ajax({ url: request_doc })
                .success(function () { populateExtraThumbs(other_page_num); })
                .error(function () { alert("Could not load page content"); })
    }
}

function populateExtraThumbs(other_page_num) {

    var xmlDoc = jqxhr.responseXML.documentElement;

    if (xmlDoc.getElementsByTagName("movie").length > 0) {

        // populating extra movie array from other page
        var other_page_movie_array = new Array();

        for (var i = 0; i < xmlDoc.getElementsByTagName("movie").length; i++) {

            var current_movie = xmlDoc.getElementsByTagName("movie")[i];

            other_page_movie_array[i] = new Object();
            other_page_movie_array[i].id_ = getNodeValue(current_movie, 'movie_id');
            other_page_movie_array[i].embed_code = getNodeValue(current_movie, 'embed_code');
            other_page_movie_array[i].thumbnail_img = new Image();
            other_page_movie_array[i].thumbnail_img.src = getNodeValue(current_movie, 'thumbnail_img');
            other_page_movie_array[i].title_ = getNodeValue(current_movie, 'movie_title');
            other_page_movie_array[i].subtitle_ = getNodeValue(current_movie, 'movie_subtitle');
            other_page_movie_array[i].description_html = getNodeValue(current_movie, 'movie_description');
        }

        var other_page_name = menu_item_array[other_page_num].page_;
        var random_thumbs_array = new Array();
        var ammount_of_thumbs = 4;
        if (other_page_movie_array.length < 4)
            ammount_of_thumbs = other_page_movie_array.length;

        while (getArrayLength(random_thumbs_array) < ammount_of_thumbs) {
            var random_movie_num = randomFromTo(0, (other_page_movie_array.length - 1));
            random_thumbs_array[other_page_name + "_" + random_movie_num] = other_page_movie_array[random_movie_num];
        }
        var random_thumbs_array_length = getArrayLength(random_thumbs_array);

        // adding new table to page
        var table_container = document.getElementById('right_content_td');

        var container_div = document.createElement('div');
        container_div.className = 'related_vids_div';

        var header_div = document.createElement('div');
        header_div.className = 'more_from_div';

        header_div.innerHTML = menu_item_array[other_page_num].text_;

        var thumbs_div = document.createElement('div');
        thumbs_div.className = 'vid_thumb_div';

        var thumbs_table = document.createElement('table');
        thumbs_table.setAttribute('border', '0');
        thumbs_table.setAttribute('cellpadding', '0');
        thumbs_table.setAttribute('cellspacing', '0');
        thumbs_table.className = 'vid_thumb_table';


        // adding single row of thumbnails to page
        var current_thumb_tr = document.createElement('tr');

        var td_counter = 0;


        for (e in random_thumbs_array) {

            var thumb_td = document.createElement('td');
            thumb_td.className = 'vid_thumb_td';

            var thumb_link = document.createElement('a');

            thumb_link.href = current_html_doc + '?page=' + menu_item_array[other_page_num].page_ + '&show_video=' + random_thumbs_array[e].id_;

            var thumb_img = random_thumbs_array[e].thumbnail_img;

            thumb_link.appendChild(thumb_img);
            thumb_td.appendChild(thumb_link);

            var vid_title_div = document.createElement('div');
            vid_title_div.className = 'vid_thumb_info_div';
            var vid_title_span = document.createElement('span');
            vid_title_span.innerHTML = random_thumbs_array[e].title_ + '/';
            var vid_subtitle_span = document.createElement('span');
            vid_subtitle_span.className = 'vid_thumb_subtitle_span';
            vid_subtitle_span.innerHTML = random_thumbs_array[e].subtitle_;
            vid_title_div.appendChild(vid_title_span);
            vid_title_div.appendChild(vid_subtitle_span);
            thumb_td.appendChild(vid_title_div);
            current_thumb_tr.appendChild(thumb_td);
        }
        
        thumbs_table.appendChild(current_thumb_tr);

        thumbs_div.appendChild(thumbs_table);
        container_div.appendChild(header_div);
        container_div.appendChild(thumbs_div);
        
        table_container.appendChild(container_div);
    }

    addThumbsFromOtherPage();
}

var movie_array = new Array();
var movie_shown = "false";
function populateContent() {
    var xmlDoc = jqxhr.responseXML.documentElement;

    // checking for and placing custom page content
    if (checkItemNode(xmlDoc, 'page_content')) {
        var custom_page_content_holder = document.getElementById('custom_content_div');
        custom_page_content_holder.innerHTML = getNodeValue(xmlDoc, 'page_content');
        custom_page_content_holder.style.display = 'block';
    }

    // populating movie array

    for (var i = 0; i < xmlDoc.getElementsByTagName("movie").length; i++) {

        var current_movie = xmlDoc.getElementsByTagName("movie")[i];

        movie_array[i] = new Object();
        movie_array[i].id_ = getNodeValue(current_movie, 'movie_id');
        movie_array[i].embed_code = getNodeValue(current_movie, 'embed_code');
        movie_array[i].thumbnail_img = new Image();
        movie_array[i].thumbnail_img.src = getNodeValue(current_movie, 'thumbnail_img');
        movie_array[i].title_ = getNodeValue(current_movie, 'movie_title');
        movie_array[i].subtitle_ = getNodeValue(current_movie, 'movie_subtitle');
        movie_array[i].description_html = getNodeValue(current_movie, 'movie_description');
    }

    // checking if one movie only
    if ((movie_array.length == 1) || args_array['show_video'])
        showVideo();

    if (movie_array.length > 1) {
        if ((movie_shown != "false") && (movie_array.length > 1)) {
            // adding single row of thumbnails to page
            var current_thumb_tr = document.createElement('tr');

            var thumb_parent_table = document.getElementById('vid_thumb_table');
            var td_counter = 0;


            var current_movie_thumb = movie_shown - 2;

            // checking if there are 2 movies after shown one - if not show previous movies' thumbnails.
            if ((movie_array.length - (movie_shown + 1)) < 2) {
                var t_ = (movie_array.length - (movie_shown + 1)) - 2;
                current_movie_thumb = current_movie_thumb + t_;
            }


            while (td_counter < 4) {
                if (current_movie_thumb > (movie_array.length - 1)) break;

                if ((movie_array[current_movie_thumb]) && (current_movie_thumb != movie_shown)) {
                    var thumb_td = document.createElement('td');
                    thumb_td.className = 'vid_thumb_td';

                    var thumb_link = document.createElement('a');

                    thumb_link.href = current_html_doc + '?page=' + current_page + '&show_video=' + movie_array[current_movie_thumb].id_;

                    var thumb_img = movie_array[current_movie_thumb].thumbnail_img

                    thumb_link.appendChild(thumb_img);
                    thumb_td.appendChild(thumb_link);

                    var vid_title_div = document.createElement('div');
                    vid_title_div.className = 'vid_thumb_info_div';
                    var vid_title_span = document.createElement('span');
                    vid_title_span.innerHTML = movie_array[current_movie_thumb].title_ + '/';
                    var vid_subtitle_span = document.createElement('span');
                    vid_subtitle_span.className = 'vid_thumb_subtitle_span';
                    vid_subtitle_span.innerHTML = movie_array[current_movie_thumb].subtitle_;
                    vid_title_div.appendChild(vid_title_span);
                    vid_title_div.appendChild(vid_subtitle_span);
                    thumb_td.appendChild(vid_title_div);
                    current_thumb_tr.appendChild(thumb_td);

                    current_movie_thumb++;
                    td_counter++;
                }
                else {
                    current_movie_thumb++;
                }
            }

            thumb_parent_table.appendChild(current_thumb_tr);
        }
        else {
            // adding all thumbnails to page
            var current_row = 0;
            var current_thumb_tr;

            var thumb_parent_table = document.getElementById('vid_thumb_table');

            var new_row = true;
            for (var j = 0; j < movie_array.length; j++) {
                if ((j % 4) == 0) {
                    new_row = true;
                    current_thumb_tr = document.createElement('tr');
                }


                var thumb_td = document.createElement('td');
                thumb_td.className = 'vid_thumb_td';

                var thumb_link = document.createElement('a');
                thumb_link.href = current_html_doc + '?page=' + current_page + '&show_video=' + movie_array[j].id_;

                var thumb_img = movie_array[j].thumbnail_img

                thumb_link.appendChild(thumb_img);
                thumb_td.appendChild(thumb_link);

                var vid_title_div = document.createElement('div');
                vid_title_div.className = 'vid_thumb_info_div';
                var vid_title_span = document.createElement('span');
                vid_title_span.innerHTML = movie_array[j].title_ + '/';
                var vid_subtitle_span = document.createElement('span');
                vid_subtitle_span.className = 'vid_thumb_subtitle_span';
                vid_subtitle_span.innerHTML = movie_array[j].subtitle_;
                vid_title_div.appendChild(vid_title_span);
                vid_title_div.appendChild(vid_subtitle_span);
                thumb_td.appendChild(vid_title_div);
                current_thumb_tr.appendChild(thumb_td);

                if (((j + 1) % 4) == 0) {
                    new_row = false;
                    thumb_parent_table.appendChild(current_thumb_tr);
                }
            }

            if (new_row)
                thumb_parent_table.appendChild(current_thumb_tr);
        }
    }

    // IF FIRST PAGE THEN LOAD THUMBNAILS FROM THE REST OF THE PAGES
    if (menu_item_currently_selected == 0)
        addThumbsFromOtherPage();
}


var menu_item_currently_selected = false;
var menu_item_array = new Array();
function placeMenuItems(xmlDoc) {
    // populating menu array
    for (var i = 0; i < xmlDoc.getElementsByTagName("menu_link").length; i++) {
        var current_menu_item = xmlDoc.getElementsByTagName("menu_link")[i];

        menu_item_array[i] = new Object();
        menu_item_array[i].text_ = getNodeValue(current_menu_item, 'link_text');
        menu_item_array[i].page_ = getNodeValue(current_menu_item, 'link_page');
        menu_item_array[i].link_seperator_ = false;
        if (checkItemNode(current_menu_item, "link_seperator")) {
            if (getNodeValue(current_menu_item, "link_seperator").toLowerCase() == "true")
                menu_item_array[i].link_seperator_ = true;
        }
    }


    var menu_parent = document.getElementById('left_menu_holder_td');

    // creating menu elements from array
    for (var j = 0; j < menu_item_array.length; j++) {

        //creating menu item DIV
        var menu_item_div = document.createElement('div');
        menu_item_div.setAttribute('id', 'menu_link' + j);
        if (j == 0)
            menu_item_div.className = "first_left_menu_link_div";
        else
            menu_item_div.className = "left_menu_link_div";

        if (menu_item_array[j].link_seperator_) {
            menu_item_div.className += ' menu_link_seperator';
        }

        if (args_array['page']) {
            if (args_array['page'] == menu_item_array[j].page_) {
                menu_item_div.className += ' selected_menu_link';
                menu_item_currently_selected = j;
            }
        }
        // creating menu item Link
        var menu_item_link = document.createElement('a');
        var link_ = current_html_doc + '?page=' + menu_item_array[j].page_;

        menu_item_link.setAttribute('href', link_);
        menu_item_link.innerHTML = menu_item_array[j].text_;

        menu_item_div.appendChild(menu_item_link);

        menu_parent.appendChild(menu_item_div);
    }

    if (menu_item_currently_selected == false) {
        document.getElementById('menu_link0').className += ' selected_menu_link';
        menu_item_currently_selected == 0;
    }
}

function placeContactInfo(xmlDoc) {
    var contact_address = false;
    if (checkItemNode(xmlDoc, "address")) {
        contact_address = getNodeValue(xmlDoc, "address");
    }
    var contact_email = getNodeValue(xmlDoc, "email");

    var contact_phone_array = new Array();

    for (var i = 0; i < xmlDoc.getElementsByTagName("phone").length; i++) {
        var current_phone = xmlDoc.getElementsByTagName("phone")[i];
        contact_phone_array[i] = new Object();
        contact_phone_array[i].text_ = getNodeValue(current_phone, 'phone_text');
        contact_phone_array[i].num_ = getNodeValue(current_phone, 'phone_num');
    }

    var phones_html = "";
    for (var j = 0; j < contact_phone_array.length; j++) {
        phones_html += contact_phone_array[j].text_ + ": <b>" + contact_phone_array[j].num_;

        if (j != (contact_phone_array.length - 1))
            phones_html += "   |  </b>";
        else
            phones_html += "</b><br />";
    }


    if (contact_address)
        phones_html += "<b>" + contact_address + " | </b>";
    phones_html += "email: <b>" + contact_email + "</b>";

    document.getElementById('contact_info_div').innerHTML = phones_html;
}

function placeLogoImg(xmlDoc) {
    var logo_img_src = getNodeValue(xmlDoc, "logo_img")

    var logo_a_tag = document.createElement('a');
    logo_a_tag.setAttribute('id', 'logo_link');
    logo_a_tag.setAttribute('href', current_html_doc);

    var logo_img_element = new Image();
    logo_img_element.src = logo_img_src;

    logo_a_tag.appendChild(logo_img_element);
    document.getElementById('logo_div').appendChild(logo_a_tag);
}



/*** Placing arg and value from URL to an array ***/

var args_array = getArgsFromUrl();

function getArgsFromUrl() {
    var args = new Object();
    var query = location.search.substring(1);
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        if (argname != "ans_message")
            args[argname] = unescape(value);
        else
            args[argname] = value;
    }
    return args;
}


/********* General AJAX functions ***********/

function getNodeAttributeValue(obj, tag, attr) {
    var return_value;

    try {
        return_value = obj.getElementsByTagName(tag)[0].getAttribute(attr);
    }
    catch (e) {
        return_value = null;
    }

    return return_value;
}

function getNodeChild(obj, tag) {
    var return_node;

    try {
        return_node = obj.getElementsByTagName(tag)[0];
    }
    catch (e) {
        return_node = obj.getElementsByTagName(tag)[0];
    }

    return return_node;
}

function getNodeValue(obj, tag) {
    var return_value;

    try {
        return_value = obj.getElementsByTagName(tag)[0].childNodes[1].nodeValue;
    }
    catch (e) {
        return_value = obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
    }

    return return_value;
}

function checkItemNode(obj, tag) {
    var item_exits = true;
    var item_data = '';
    try {
        item_data = getNodeValue(obj, tag);
    }
    catch (e) {
        item_exits = false;
    }

    if (item_data == '')
        item_exits = false;

    return item_exits;
}

function randomFromTo(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}

function getArrayLength(arr) {
    var element_count = 0;

    for (e in arr) { element_count++; }

    return element_count;
}
