/* $Rev: 3634 $ */
/* non particles ver 1996 */
var mouseOverChecklist=true;
var spanNodeAppendix='-options-container';
var inputDefaultValue='- Any -';

function selectClickEventHandler (checklistObj,event,arrayChecklist) {
    if (checklistObj.visible==false) {
        $.each(arrayChecklist,function(i,v) {
            if (checklistObj.checklist!=v.checklist && v.visible==true) {hideChecklist(v);}
        });
        if (checklistObj.spanCheckboxContainerJQ==null) {
            checklistBlockJQ=ajaxFormRequest(checklistObj,true);
            showChecklist(checklistObj,checklistObj.spanCheckboxContainerJQ,event,arrayChecklist);
        }
        else {showChecklist(checklistObj,checklistObj.spanCheckboxContainerJQ,event,arrayChecklist);}
    }
    else {hideChecklist(checklistObj)}
}

function ajaxFormRequest(checklistObj,showProgressStatus) {
    if (showProgressStatus) {showProgress(true);}
    var dataToSend="mode=ajax-search&id="+checklistObj.id;
    var spanNodeID=checklistObj.spanCheckboxContainerId;
    var spanNode='<span style="display:none;" id="'+spanNodeID+'"></span>';
    checklistObj.checklist.append(spanNode);
    var jqSpanNode=checklistObj.spanCheckboxContainerJQ=$('#'+spanNodeID);
    var html = search_from_options[checklistObj.id];
    jqSpanNode.html(html);
	var checklistName=checklistObj.inputId;
	if (checklistName=='type') {
		var multiul1 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(0).outerWidth();
		var multiul2 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(1).outerWidth();
		var multiul3 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(2).outerWidth();
		var multiul4 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(3).outerWidth();
		multiul = multiul1 + multiul2 + multiul3 + multiul4;
		$('#productTypeChecklist-options-container .checklist-options').css({
			'width': multiul + 10  + 'px'
		});
	}
	if (jQuery.browser.mozilla && jQuery.browser.version < '1.9') {
		if (checklistName=='cat' || checklistName=='author') {
			jqSpanNode.children('.checklist-options').css('width',checklistObj.ff2width+'px');
		}
	}
	if (showProgressStatus) {showProgress(false);}
    addEventListeners(checklistObj);
    return jqSpanNode
}

function addEventListeners(checklistObj) {
    $('.button.checkAll').live('click',function() {changeCheckbox(checklistObj,$(this).parents('.checklist-widget'),true);});

    $('.button.uncheckAll').live('click',function() {changeCheckbox(checklistObj,$(this).parents('.checklist-widget'),false);});

    $('.button.btn-apply').live('click',function() {
        mouseOverChecklist=false;
        $('body').trigger('click');
    });

    var inputRange ='';
    if (checklistObj.id == 'productTypeChecklist') {
        inputRange='.multilevel >li ul li input[type=checkbox]';
    }
    else {
        inputRange='input[type=checkbox]';
    }
    $(inputRange,checklistObj.checklist).live('click',function() {
        var currentCheckboxValue=$.trim($(this).parent().text());
        var currentSelectValue=$.trim(checklistObj.valueKeeper.text());
        var tempValue='';
        if ($(this).attr('checked')) {
            if (currentSelectValue==checklistObj.defaultValue) {
                tempValue=currentCheckboxValue;
            }
            else {
                tempValue=currentSelectValue+', '+currentCheckboxValue;
            }       
        }
        else {
            currrentStringPosition=currentSelectValue.indexOf(currentCheckboxValue, 0);
            if (currrentStringPosition==0) {
                if (currentCheckboxValue.length==currentSelectValue.length) {
                    tempValue=currentSelectValue.substr(currrentStringPosition+currentCheckboxValue.length);
                }
                else {
                    tempValue=currentSelectValue.substr(currrentStringPosition+currentCheckboxValue.length+2);
                }
            }
            else {
                firstPartTempValue=currentSelectValue.substr(0,currrentStringPosition-2);
                secondPartTempValue=currentSelectValue.substr(currrentStringPosition+currentCheckboxValue.length);
                tempValue=firstPartTempValue+secondPartTempValue;
            }
        }
        if (tempValue=='') {tempValue=checklistObj.defaultValue;}
        checklistObj.valueKeeper.text(tempValue);
    });

    $('.checklist-options .multilevel >li input:first-child').live('click',function(){
        currentCheckbox=$(this);
        if (currentCheckbox.is(':checked')) {changeCheckbox(checklistObj,currentCheckbox.parents('li:first'),true);}
        else {changeCheckbox(checklistObj,currentCheckbox.parents('li:first'),false);}
    });
    $('.checklist-options .multilevel >li ul li input[type=checkbox]').live('click', function(){
        var element=$(this).parent().parent().parent().parent().find('input[type=checkbox]:first');
        var currentSelectValue=checklistObj.valueKeeper;
        var tempValue='';
        if ($(this).parents('ul:first').find('li input[type=checkbox]').size()==$(this).parents('ul:first').find('li input[type=checkbox]:checked').size()) {
            if (!element.is(':checked')) {
                element.attr('checked',true);
                tempValue=$.trim(element.parent().text())+', '+currentSelectValue.text();
                currentSelectValue.text(tempValue);
            }
        } else {
            if (element.is(':checked')) {
                element.attr('checked',false);
                if ($('input[type=checkbox]:checked',checklistObj.checklist).size()==0) {
                    currentSelectValue.text(checklistObj.defaultValue);
                }
                else {
                    var values='';
                    $('input[type=checkbox]:checked',checklistObj.checklist).each(function() {
                        if (values=='') {
                            values=$.trim($(this).parent().text());
                        }
                        else {
                            values=values+', '+$.trim($(this).parent().text());
                        }
                        currentSelectValue.text(values);
            });
                }
            }
        }
    });
}

function showProgress(state) {
    var searchFormContainer=document.getElementById('sform_container');
    var loadProgress=document.getElementById('loadProgress');
    if (state) {
        searchFormContainer.style.position='relative';
        loadProgress.style.display='block';
    }
    else {
        searchFormContainer.style.position='static';
        loadProgress.style.display='none';
    }
}

function showChecklist(checklistObj,checklistJqObj,event,arrayChecklist) {
		 animateScroll();
     var checklistName=checklistObj.inputId;
						if (checklistName=='type') {
							checklistJqObj.css('display','block');
						var multiul1 = $('ul.multilevel').outerWidth();
						var multiul2 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(1).outerWidth();
						var multiul3 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(2).outerWidth();
						var multiul4 = $('#productTypeChecklist-options-container .checklist-options ul.multilevel').eq(3).outerWidth();
						var multiul = multiul1 + multiul2 + multiul3 + multiul4;
		if (multiul < '400') {
							if ($.browser.msie && $.browser.version==6 || $.browser.msie && $.browser.version==7) {
								$('#productTypeChecklist-options-container .checklist-options').css({
											'width': multiul + 425  + 'px'
									});
							} else {
								$('#productTypeChecklist-options-container .checklist-options').css({
											'width': multiul + 394  + 'px'
									});
							}
						} else {
                    $('#productTypeChecklist-options-container .checklist-options').css({
											'width': multiul + 10  + 'px'
									});
									}

						} else {
							checklistJqObj.css('display','block');
						}
    checklistObj.checklist.bind('mouseenter',function() {mouseOverChecklist=true;});
    checklistObj.checklist.bind('mouseleave',function() {mouseOverChecklist=false;});
    checklistObj.visible=true;
    mouseOverChecklist=true;
    waitForChecklistBlur(event,arrayChecklist);
}

function hideChecklist(checklistObj) {
    checklistObj.checklist.unbind('mouseenter');
    checklistObj.checklist.unbind('mouseleave');
    checklistObj.spanCheckboxContainerJQ.css('display','none');
    checklistObj.visible=false;
    $('body').unbind('click');
}

function waitForChecklistBlur(event,arrayChecklist) {
    event.stopPropagation();
    $('body').bind('click',function() {if (mouseOverChecklist==false) {hideAllChecklist(arrayChecklist);}});
}

function hideAllChecklist(arrayChecklist) {
    $('#searchFormResetButton').css('display','none');
    $.each(arrayChecklist,function(i,v) {
        if (v.visible==true) {
            v.spanCheckboxContainerJQ.css('display','none');
            v.visible=false;
        }
        if ($('input[type=checkbox]:checked',v.checklist).size()>0) {$('#searchFormResetButton').css('display','block');}
        else {$('#'+v.inputId).val('');}
    });
    $('body').unbind('click');
    checkResetButtonShow();
}

function changeCheckbox(checklistObj,checkboxRange,status) {
    checklistGroup=$('input[type=checkbox]',checkboxRange);
    checklistGroup.attr('checked',status);
    var values='';
    if (status) {
        if (checkboxRange==checklistObj.checklist) {
            $('#'+checklistObj.id+' ul li label').each(function() {
                if (values=='') {
                    values=$.trim($(this).text());
                }
                else {
                    values=values+', '+$.trim($(this).text());
                }
            });
            
        }
        else {
            $('input[type=checkbox]:checked',checklistObj.checklist).each(function() {
                if (values=='') {
                    values=$.trim($(this).parent().text());
                }
                else {
                    values=values+', '+$.trim($(this).parent().text());
                }
            });
        }
        checklistObj.valueKeeper.text(values);
    }
    else {
        $('input[type=checkbox]:checked',checklistObj.checklist).each(function() {
            if (values=='') {
                values=$.trim($(this).parent().text());
            }
            else {
                values=values+', '+$.trim($(this).parent().text());
            }
        });
        checklistObj.valueKeeper.text(values);
    }
    if ($('input[type=checkbox]:checked',checklistObj.checklist).size()==0) {
        checklistObj.valueKeeper.text(checklistObj.defaultValue);
    }
}

function checkResetButtonShow() {
	var resetButtonVisible = false;
	if (
			(0 != $('#productTypeChecklist-options-container input.input_format_1:checked').length) ||
			(0 != $('#categoryChecklist-options-container input.input_format_1:checked').length) ||
			(0 != $('#styleChecklist-options-container input.input_format_1:checked').length) ||
			(0 != $('#authorChecklist-options-container input.input_format_1:checked').length) ||
			(0 != $('#colour-selector input[type=checkbox]:checked').length) ||
			('- Any -' != $('#tid_field').val()) ||
			('- Any -' != $('#search_words_field').val()) ||
			('- Any -' != $('#from_field').val()) ||
			('- Any -' != $('#to_field').val())
		) {
		resetButtonVisible = true;
	}
	$('#searchFormResetButton').css('display', (resetButtonVisible ? 'block' : 'none'));
}

function animateScroll() {
    var headerOffset=$('#search-form').offset().top;
    if ($.browser.webkit) {
        $('body').animate({scrollTop: headerOffset}, 1300);
    } else {
        $('html').animate({scrollTop: headerOffset}, 1300);
    }
}

function collectCheckboxValues(checklistObj) {
    if (checklistObj.spanCheckboxContainerJQ!=null) {
        checkboxes=$('input[type=checkbox]:checked',checklistObj.spanCheckboxContainerJQ)
        if (checkboxes.size()>0) {
            values='';
            checkboxes.each(function(){
                if (values.length==0) {values=values+$(this).val();}
                else {values=values+','+$(this).val();}
            });
            document.getElementById(checklistObj.inputId).value=values;
        }
    }
}

$(function() {
    var formContainer=$('#sform_container');
    formContainer.append('<div id="loadProgress" style="display:none"></div>');
    var productType=new Object();
        productType.checklist=$('#productTypeChecklist');
        productType.id=productType.checklist.attr('id');
        productType.valueKeeper=$('#'+productType.id+' .checklist-select-value');
        productType.defaultValue='- Any Product -';
        productType.visible=false;
        productType.spanCheckboxContainerId=productType.id+spanNodeAppendix;
        productType.spanCheckboxContainerJQ=null;
        productType.inputId='type';
        productType.ff2width=400;
    var productCategory=new Object();
        productCategory.checklist=$('#categoryChecklist');
        productCategory.id=productCategory.checklist.attr('id');
        productCategory.valueKeeper=$('#'+productCategory.id+' .checklist-select-value');
        productCategory.defaultValue='- Any Category -';
        productCategory.visible=false;
        productCategory.spanCheckboxContainerId=productCategory.id+spanNodeAppendix;
        productCategory.spanCheckboxContainerJQ=null;
        productCategory.inputId='cat';
        productCategory.ff2width=755;
    var productStyle=new Object();
        productStyle.checklist=$('#styleChecklist');
        productStyle.id=productStyle.checklist.attr('id');
        productStyle.valueKeeper=$('#'+productStyle.id+' .checklist-select-value');
        productStyle.defaultValue='- Any Style -';
        productStyle.visible=false;
        productStyle.spanCheckboxContainerId=productStyle.id+spanNodeAppendix;
        productStyle.spanCheckboxContainerJQ=null;
        productStyle.inputId='style';
        productStyle.ff2width=350;
    var productAuthor=new Object();
        productAuthor.checklist=$('#authorChecklist');
        productAuthor.id=productAuthor.checklist.attr('id');
        productAuthor.valueKeeper=$('#'+productAuthor.id+' .checklist-select-value');
        productAuthor.defaultValue='- Any Author -';
        productAuthor.visible=false;
        productAuthor.spanCheckboxContainerId=productAuthor.id+spanNodeAppendix;
        productAuthor.spanCheckboxContainerJQ=null;
        productAuthor.inputId='author';
        productAuthor.ff2width=620;

    var ajaxChecklistGroup=new Array(productType,productCategory,productStyle,productAuthor);

    var tid_field=$('#tid_field');
    var search_words_field=$('#search_words_field');
    var from_field=$('#from_field');
    var to_field=$('#to_field');
    var inputsGroup=new Array(tid_field,search_words_field,from_field,to_field);

    var searchFormSubmit=$('#searchFormSubmit');
    var searchFormResetButton=$('#searchFormResetButton');
    var colorSearch=$('#colour-selector');
    var searchForm=$('#searchForm');

    searchFormSubmit.click(function() {searchForm.submit();});

    searchForm.submit(function() {
        $.each(ajaxChecklistGroup,function(index,value) {collectCheckboxValues(value);});
    });
        
    searchFormResetButton.click(function(){
        $('#colour-selector li').removeClass('checked');
        $('#colour-selector input[type=checkbox]:checked').attr('checked', false);
        $.each(ajaxChecklistGroup,function(i,v) {
            $('input[type=checkbox]:checked',v.checklist).attr('checked', false);
            v.valueKeeper.text(v.defaultValue);
            $('#'+v.inputId).val('');
        });
        $.each(inputsGroup,function(i,v) {v.val(inputDefaultValue).css('text-align','center');});
        checkResetButtonShow();
    });

    $.each(ajaxChecklistGroup, function(index,value) {
        value.checklist.children().click(function(event) {selectClickEventHandler(value,event,ajaxChecklistGroup)});
        if ($('#'+value.inputId).val()!='') {
            var tempArray=$('#'+value.inputId).val().split(',');
            ajaxFormRequest(value,false)
            $('input[type=checkbox]',value.checklist).ready(function() {
                $.each(tempArray,function(i,v) {$('input[value="'+v+'"]',value.checklist).attr('checked',true);});
            });
        }
    });

    checkResetButtonShow();

    $.each(inputsGroup, function(index,value) {
        value.focus(function() {
            if ($(this).val()==inputDefaultValue) {value.val('').css('text-align','left');}
        });
        value.blur(function() {
            if ($(this).val()=='') {value.val(inputDefaultValue).css('text-align','center');}
            else if ($(this).val()==inputDefaultValue) {value.css('text-align','center');}
            checkResetButtonShow();
        }).keypress(function(e) {
            var code = e.keyCode || e.which;
            if(code == 13) {searchForm.submit();}
        });
    });

    $('#colour-selector li span').click(function(event){
        var checked = $(this).parent().hasClass('checked');
        if (!checked && $('#colour-selector input[type=checkbox]:checked').size()>=3) {
            alert('You may not use more colors for search!');
        }
        else {
            $(this).parent().toggleClass('checked');
            $(this).next().attr('checked', $(this).parent().hasClass('checked'));
            checkResetButtonShow();
        }
    });
});

