/*
 * Community
 * http://lovefilm.com
 * Version 0.1.0
 */

function closeBoxes(boxes) {
    for (var i=0; i<boxes.length; i++) {
        boxes[i].style.display = 'none';
    }
}

function init() {
    var listBoxes = document.getElementsByClassName('view');
    var listLinks = document.getElementsByClassName('open_list');
    closeBoxes(listBoxes);
    for (var i=0; i<listLinks.length; i++) {
        listLinks[i].onclick = function () {
            closeBoxes(listBoxes);
            alert(this.id);
        };
    }
}

// *************************************************************************
//		 ___________________________________________________________		#
//		|															|		#
//		|	NEW Ajax Community List Features					    |		#
//		|___________________________________________________________|		#
//																			#
// *************************************************************************

var listItemId;
var listItemName;
var sendtolistID;

function loadRightListPanelData(originalRequest) {
    $('#active_list').innerHTML = originalRequest.responseText;
}

function loadRightListPanel(sendtolistID, startHidden) {
    $.ajax ({
            method: 'get',
			url:'/community/amend.html', 
            data: 'action=refresh-side-list&start_hidden=' + startHidden,
            success: loadRightListPanelData
        });
    return false;
}

function switchRightListPanel(clid) {
    var myAjax = new Ajax.Request(
        '/community/amend.html', {
            method: 'get',
            parameters: 'action=switch-side-list&customer_list_id='+clid,
            onComplete: loadRightListPanelData
        }
    );
    return false;
}

function loadSearchResults(originalRequest) {
    $('search_results').innerHTML = originalRequest.responseText;
    window.effect.cancel();
    window.effect = new Effect.Appear($('search_results'));
}

function listSearchResult(search_keywords, clid) {
    $('search_results').innerHTML = 'searching...';
    window.effect = new Effect.Pulsate($('search_results'));
    var myAjax = new Ajax.Request(
        '/community/amend.html', {
            method: 'get',
            parameters: 'action=list-search-results&customer_list_id='+clid+'&search_keywords='+search_keywords,
            onComplete: loadSearchResults
        }
    );
    return false;
}

function addToMylist(listId,productId,name) {
    sendtolistID = listId;
    listItemId = productId;
    listItemName = unescape(name);
    $.ajax({
            method: 'get',
            url: '/community/amend.html',
			data: 'action=add-list-item&customer_list_id='+listId+'&product_id='+productId+'&comment='+name,
            success: addToMylistParseXML
        });
    return false;
}

function addToMylistParseXML(originalRequest) {
    var currentList;
    if (typeof( RIGHT_LIST_ID ) != "undefined") {
        currentList = RIGHT_LIST_ID;
    }
    if (currentList == sendtolistID) {
        $('#open_list').append('<li id=\'list_item_added\'><a href="/product/detail.html?product_id='+listItemId+'">'+listItemName+'</a></li>');

    } else {
        RIGHT_LIST_ID == sendtolistID;
        loadRightListPanel(sendtolistID, 0);
    }
}

function addToManageList(listId,productId,name) {
    sendtolistID = listId;
    listItemId = productId;
    listItemName = unescape(name);
    var myAjax = new Ajax.Request(
        '/ajax/alter_customer_collection_lists.html', {
            method: 'get',
            parameters: 'action=add-list-item&customer_list_id='+listId+'&product_id='+productId,
            onComplete: addToManageListParseXML
        }
    );
    return false;
}

function addToManageListParseXML(originalRequest) {
    var html = '<li id="managelist_'+listItemId+'"><span class="handle" title="drag me up or down!">'+listItemName+'</span><div style="background-color: #F7F7F7;margin:0 0 20px 0"><i><span id="listComment_'+listItemId+'" style="cursor: pointer">Enter comments by clicking here...</span></i></div></li>';
    new Insertion.Bottom ($('managelist'), html);
    new Effect.SwitchOff($('searchlist_'+listItemId));
    EditInPlace.makeEditable({ 
        id: 'listComment_'+listItemId,
        type: 'textarea',
        select_text: true,
        ajax_data: {
            action: 'update-list-item',
            product_id: listItemId,
            customer_list_id: sendtolistID,
            rank: ''
        }
    });
    Sortable.create('managelist', {
            dropOnEmpty: true,
            handle:'handle',
            constraint:'vertical',
            onUpdate: submit_serialized_list
    });
    $('update_message').innerHTML = '<strong>Added: \''+listItemName+'\' to your collection.</strong>';
    new Effect.Highlight($('update_message'));
    if(manage_list_empty) {
        manage_list_empty = 0;
        new Effect.SwitchOff($('new_collection_message'));
        new Effect.Appear($('view_collection_button'));
    }
}

function remove_from_list(mcid, action, clid, product_id) {
    if (!confirm("Are you sure?")) return;
    var pars = "mangled_customer_id="+mcid+"&action="+action+"&customer_list_id="+clid+"&product_id="+product_id;
    var myAjax = new Ajax.Request(
        '/community/amend.html', {
            method: 'get',
            parameters: pars,
            onComplete: new Effect.SwitchOff($('managelist_'+product_id))
        }
    );
}

function confirmUpdatedRanks() {
    $('update_message').innerHTML = '<strong>Sort order updated</strong>';
    new Effect.Highlight($('update_message'));
}

// *************************************************************************
//		 ___________________________________________________________		#
//		|															|		#
//		|	Ajax Community List Features						    |		#
//		|___________________________________________________________|		#
//																			#
// *************************************************************************
req = null;

function updateList(formData) {
    if (getHTTPObject()) {
        listFunction(formData.action.value,formData.mangled_customer_id.value,formData.customer_list_id.value,formData.product_id.value,'','','');
    }
}

function linkText(action,customer,list,product,listPage,rank,comment) {
    var html = ' href="#" onClick="listFunction(';
    html += '\'' + action + '\',\'' + customer +  '\',\'' + list +  '\',\'' + product +  '\',\'' + listPage +  '\',\'' + rank  +  '\',\'' + comment + '\')">';
    return html;
}

function listFunction(listAction,mangledCustomerId,listId,productId,listPage,rank,comment) {
    if (getHTTPObject()) {
        var url = '/community/amend.html?action=' + listAction;
        var updateLists = 1;

        if (listId) {
            url += '&customer_list_id=' + listId;
        }
        if (productId) {
            url += '&product_id=' + productId;
        }
        if (rank) {
            url += '&rank=' + rank;
        }
        if (comment) {
            url += '&' + productId + '_comment=' + comment;
        }

        url += '&mangled_customer_id=' + mangledCustomerId + '&fr=' + Math.random();
        req = getHTTPObject();
        if (listPage == 1) {
            req.onreadystatechange = pageFunction_response;
        } else {
            req.onreadystatechange = listFunction_response;
        }
        req.open('get',url, true);
        req.send(null);
        return false;
    } else {
        return true;
    }
}

function listFunction_response() {
    if (req.readyState == 4) {
        if (req.status == 200 && req.responseXML) {
            var openList = req.responseXML.getElementsByTagName("openlist");
            var item = req.responseXML.getElementsByTagName("item");
            var listItems = '';

            for (var i=0; i<item.length; i++) {
                listItems += '<li><a href="/product/detail.html?product_id=' + item[i].getAttribute("id") + '" title="' + item[i].getAttribute("comment") + '">' + item[i].getAttribute("title") + '</a></li>';
            }

            document.getElementById('open_list').innerHTML = listItems;
            document.getElementById(openList[0].getAttribute("product") + '_action').value = openList[0].getAttribute("added") + '-list-item';
            document.getElementById(openList[0].getAttribute("product") + '_add').src = '/images/icons/' + openList[0].getAttribute("added") + '-list-item.gif';
        }
        req = null;
    }
}

function pageFunction_response() {
    if (req.readyState == 4) {
        if (req.status == 200 && req.responseXML) {
            var list = req.responseXML.getElementsByTagName("list");
            var openList = req.responseXML.getElementsByTagName("openlist");
            var item = req.responseXML.getElementsByTagName("item");
            var listItems = '';

            for (var i=0; i<item.length; i++) {
                listItems += '<div id="' + item[i].getAttribute("id") + '" class="list_item">';
                listItems += '<a href="/community/amend.html?action=remove-list-item&customer_list_id=' + openList[0].getAttribute("id") + '&product_id=' + item[i].getAttribute("id") + '&rank=0&mangled_customer_id=' + openList[0].getAttribute("customer") + '&return_page=1"><img src="/images/icons/btn_delete.gif" alt="delete list" width="15" height="15" border="0" align="right" vspace="10" /></a>';
                listItems += '<div class="rank"><br />';
                listItems += '<a href="#"' + (i > 0 ? '' : ' style="visibility:hidden"') + linkText('update-list-item',openList[0].getAttribute("customer"),openList[0].getAttribute("id"),item[i].getAttribute("id"),'1',i,item[i].getAttribute("comment")) + '<img src="/images/icons/btn_order_up.gif" alt="move up" border="0" width="15" height="13" /></a>'
                listItems += '<input type="text" id="' + item[i].getAttribute("id") + '_rank" name="' + item[i].getAttribute("id") + '_rank" value="' + (i+1) + '" readonly="readonly" />';
                listItems += '<a href="#"' + (i < (item.length-1) ? '' :  ' style="visibility:hidden"') +linkText('update-list-item',openList[0].getAttribute("customer"),openList[0].getAttribute("id"),item[i].getAttribute("id"),'1',(i + 2),item[i].getAttribute("comment")) + '<img src="/images/icons/btn_order_dn.gif" alt="move down" border="0" width="15" height="13" /></a>'
                listItems += '</div>';
                listItems += '<a class="list_image" href="/product/detail.html?product_id=' + item[i].getAttribute("id") + '">';
                listItems += '<img src="/images/products/' + item[i].getAttribute("image") + '" alt="' + item[i].getAttribute("title") + '" width="60" height="86" align="left" border="0" /></a>';
                listItems += '<div class="list_desc"><a href="/product/detail.html?product_id=' + item[i].getAttribute("id") + '">' + item[i].getAttribute("title") + '</a>';
                listItems += '<textarea name="' + item[i].getAttribute("id") + '_comment">' + (item[i].getAttribute("comment") == '' ? 'add comment' : item[i].getAttribute("comment")) + '</textarea></div></div>'; 
            }
            document.getElementById("list_items").innerHTML = listItems;
        }
        req = null;
    }
}
