﻿

/* Device comparison */


// function used in device matrix pages
function selectDevice(target) {
    if (target != "") {
        for(i=0; i < document.forms[1].length; i++) {
            document.forms[1].elements[i].selectedIndex = 0;
        }
        document.location = target;
    }
}

// function used in device matrix pages
function filterDevice() {
    target = document.getElementById("sort").deviceSearch.options[document.getElementById("sort").deviceSearch.selectedIndex].value;
    document.location = target;
}


var itemsToCompare = new Array();
var comparisonCookieDevices = new MultiValueCookie("selectedDevices", "$", ",");

function getItemsToCompareObjectById(id) {
	for (var i=0; i<itemsToCompare.length; i++) {
		if(itemsToCompare[i].id == id) 
			return itemsToCompare[i];
	}
	return null;
}


function getSelectedIds() {
	var selectedIds = new Array();
	jQuery("#comparables .device").each(function(){
		selectedIds.push(jQuery(this).attr('id'));
	});
	return selectedIds;
}

function setSelectedComparablesCookie(){
    var comparisonCookieDevices = new MultiValueCookie("selectedDevices", "$", ",");
    comparisonCookieDevices.clear();
    jQuery("#comparables .device").each(function(){        
	var t = jQuery(this);
        comparisonCookieDevices.setValue(t.attr('id'), t.find('.devimg').eq(0).attr('alt'));
        comparisonCookieDevices.setValue(t.attr('id'), t.find('.devimg').eq(0).attr('src'));
    });
	comparisonCookieDevices.setExpirationDays(0);
    comparisonCookieDevices.save();
}

function countSelected() {
	var count = 0;
	for (var i=0; i<itemsToCompare.length; i++) {
		if(itemsToCompare[i].selected) {
			count++;
		}
	}
	return count;
}

function unselectItem(item, dontSave) {
	item.selected = false;
	jQuery("#comparables").children("#"+item.id).eq(0).remove();
	jQuery("#thumb_" + item.id).attr("class","device");
	if (!dontSave) {
		setSelectedComparablesCookie();
	}
}

function selectItem(item, dontSave) {
	item.selected = true;

	var newDeviceDiv = jQuery("<div></div>");
	newDeviceDiv.attr('id', item.id);
	newDeviceDiv.attr('class', "device added");
	var newDeviceContent = jQuery("#thumb_" + item.id).html();
	newDeviceDiv.append(newDeviceContent);
	newDeviceDiv.appendTo("#comparables");

	jQuery("#comparables #" + item.id).html(newDeviceContent+"");
	jQuery("#" + item.id + " .device-compare-btn").click(function(){
		toggleCompare(item.id);
	});
	jQuery("#thumb_" + item.id).addClass("device added");
	if (!dontSave) {
		setSelectedComparablesCookie();
	}
}

function toggleCompare(id, dontSave) {
	openComparableView();
	
	var item = getItemsToCompareObjectById(id);
	if (item.selected) {
		unselectItem(item, dontSave);
		return false;
	}

	if (countSelected() >= 5) {
		alert("You can select at maximum five devices!");
		return false;
	} 
	
	selectItem(item, dontSave);
	return true;
}

function openComparableView(){
		jQuery("#deviceComparison").attr("class", "opened");
}

function clearComparables(){
	for (var i=0; i<itemsToCompare.length; i++) {
		if(itemsToCompare[i].selected) {
			itemsToCompare[i].selected = false;
			jQuery("#comparables").children("#" + itemsToCompare[i].id).eq(0).remove();
		}
	}			
	jQuery("#deviceGrid .device").removeClass("added");

    setSelectedComparablesCookie();
}

function enableJavascriptFields(){
	jQuery(".javas").css({display: "inline"});
	jQuery(".non-javas").remove();
}


function initPhoneComparison(){

    jQuery("#deviceGrid .device").each(function(){
		var t = jQuery(this);
		var deviceId = t.attr('id').substring(6, t.attr('id').length);    
		itemsToCompare.push({id:deviceId, selected:false});
    });

    var comparisonCookieIds = comparisonCookieDevices.getIds(); 
    for (var i=0; i<comparisonCookieIds.length; i++) {
            var values = comparisonCookieDevices.getValues(comparisonCookieIds[i]);
            if (getItemsToCompareObjectById(comparisonCookieIds[i]) != null) {
                    toggleCompare(comparisonCookieIds[i], true);     
            } else {
                    itemsToCompare.push({id:comparisonCookieIds[i], selected:true});
                    var newDevice = jQuery('<div id="' + comparisonCookieIds[i] + '" class="device added"></div>');
                    newDevice.html('<a href="/devices/' + 
                            comparisonCookieIds[i] + '"><img title="' + values[0] + '" alt="' + values[0] + 
                            '" class="devimg" src="' + values[1] + 
                            '"/></a><div class="device-name"><table><tbody><tr><td><a href="/devices/' + 
                            comparisonCookieIds[i] + '">' + values[0] + 
                            '</a></td></tr></tbody></table></div><span class="device-info"></span><div title="Compare ' + 
                            values[0] + '" class="device-compare-btn javas"><span class="add">Add to comparison</span><span class="remove">Remove</span></div>');
                    
                    newDevice.appendTo("#comparables");
                    jQuery("#" + comparisonCookieIds[i] + " .device-compare-btn").click(function(){
                            toggleCompare(jQuery(this).parents('.device').eq(0).attr('id'));
                    });
            }
    }

    if (comparisonCookieIds.length > 0) {
            openComparableView();	
    }

    jQuery(".non-javas").remove();
}


function startComparison(idArray) {
	var url = '/Devices/Device_specifications/Comparison.xhtml?dev=';
	for (var i=0; i<idArray.length; i++) {
		url += idArray[i];
		if (i + 1 < idArray.length) {
			url += ',';
		}
	}

    var width  = 900;
    var height = 600;
    var left   = (screen.width  - width)/2;
    var top    = (screen.height - height)/2;
    var params = 'width='+width+', height='+height;
    params += ', top='+top+', left='+left;
    params += ', directories=no';
    params += ', location=no';
    params += ', menubar=no';
    params += ', resizable=yes';
    params += ', scrollbars=yes';
    params += ', status=no';
    params += ', toolbar=no';
    var comparisonWindow =  window.open(encodeURI(url), 'showcomparison', params);
	if (window.focus) {
        comparisonWindow.focus()
    }
}

/* end of device comparison functions */


$(document).ready(function() { 

	/* device comparison functions */
    jQuery("#toggleDeviceComparison").click(function(){
        if (jQuery("#deviceComparison").hasClass('opened')){
            jQuery("#deviceComparison").removeClass('opened');
        } else {
            jQuery("#deviceComparison").attr('class', 'opened');
        }
    });
    
    jQuery("#deviceGrid .device .device-compare-btn").click(function(){
        var thumbId = jQuery(this).parents(".device").eq(0).attr("id");
        var id = thumbId.substring(6, thumbId.length);
    	toggleCompare(id);
    });
    
    jQuery("#comparebtn").click(function(){
    	var selIds = getSelectedIds();
    	if (selIds.length<2) {
            alert("Select at least two devices for comparison!");	
        } else {  
	    startComparison(selIds);
    	}
    });

    jQuery("#clearbtn").click(function(){
		clearComparables();
    });

    var pagePath = window.location.pathname;
    var pageName = '/devices/'+pagePath.substring(pagePath.lastIndexOf('/') + 1);
    jQuery("#device-selector form select").val(pageName);

    jQuery("#device-selector form select").change(function(){
        var selectValue = this.options[this.selectedIndex].value;
        if (selectValue != ''){
            location = selectValue;
        }
    });

    initPhoneComparison();

    jQuery("#btn_compare-all").click(function(){
        var listedDeviceIds = new Array();
        jQuery("#deviceGrid .device").each(function(){
	    var id = jQuery(this).attr('id');
            listedDeviceIds.push(id.substring(6, id.length));
        });
	    startComparison(listedDeviceIds);
    });    
    
    /* end of device comparison functions */

  var i;
        var lbl='';
        for (i=1; i<4; i++){
            var f = "filter"+i;
            var qs = getQueryString(f);
 
            if (qs != null) {
 
                if (f == 'filter2' ) {
                    jQuery('#filter3').removeAttr("disabled");
                }
 
                jQuery('#'+f+' option').each(function() {
                    if(this.value == qs){
                        jQuery(this).attr('selected', 'selected');
                        // writes criteria (filter) next to 'Search result:' label
                        if (lbl != '') {
                            lbl = lbl+', ';
                        }
                        lbl = lbl + jQuery(this).html();
                    }
                });
            }          
	
		jQuery('#'+f).change(function () {
                document.location = constructUrl();
            });
 
            disableUsedOptions(i, qs);             
        } //for
 
        jQuery('#clearBtn').click(function() {
            document.location = "/Devices/Device_specifications/";
        });
    jQuery('#filterResultsLabel').html( (lbl == 'Filter Devices: Show all' || lbl == '') ? 'All' : lbl  );      						   

});

   function getQueryString(f) {
        var reg = new RegExp("(^|&)"+f+"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r!=null) return unescape(r[2]); return null;
    }
 
 
    function disableUsedOptions(id, val) {
        for (i=1; i<4; i++){
            if (i != id) {
                jQuery('#filter'+i+ ' option').each(function() {
                    if (this.value == val)
                        jQuery(this).attr('disabled', 'disabled');
                });
            }
        }
    }
     
    function constructUrl() {
        var f1 = jQuery("#filter1 option:selected").val();
        var f2 = jQuery("#filter2 option:selected").val();
        var f3 = jQuery("#filter3 option:selected").val();
        var url = '/Devices/Device_specifications/?filter1='+(f1==''?'all':f1);
        if (f2 != '') {
            url = url+"&filter2="+f2;
            if (f3 != '') {
                url = url+"&filter3="+f3;
            }
        }
        return url;
    }


