function createOption(val,label){
	var opt = document.createElement('option');
    opt.value = val;
    opt.appendChild(document.createTextNode(label));
    return opt;
}

/******************************************************************************
 * Front end script: Creates scripts for main page blocks and injected
 * pages.
 */
$(document).ready(function() {
    var frontScript = new Front();
});

/******************************************************************************
 * Front object, that loads all other scripts.
 */
function Front()
{
    /**
     * Path to the script of the guide (document) output
     *
     * @var string
     */
    this.guidesPath = "/common/file/get-install-guide/id/";

    /**
     * Create Product Search block
     */
    this.products = new ProductSearch();

    /**
     * Create Install Guide Search block
     */
    this.guides = new InstallGuidesSearch(this.guidesPath);

    /**
     * Loading content of the injected pages
     */
    this.pageResults = new Results();

    /**
     * Create Install Guide page
     */
    this.guidesPage = new InstallGuidesPage(this.guidesPath);

    /**
     * Create Weblink Plugin page
     */
    this.pluginPage = new WeblinkPage();
    
    window.onbeforeunload = function() {
    	if (typeof(WU) != "undefined") 
    	{
    		return "It will interrupt the updating process.";
    	}
    }    
    
    window.onunload = function() {
    	WU = undefined;
    }    
}

/******************************************************************************
 * Product Search block
 */
function ProductSearch()
{
    initLabels();
    buildMakes();
    makeSelection();
    yearSelection();
    modelSelection();
    buildProducts();
    productSelection();
}

/**
 * Checking if updating is in process
 */
function CheckIfUpdating()
{
	if (typeof(WU) != "undefined") 
	{
        if (confirm("Are you sure you want to exit the updating process?"))
        {
        	WU = undefined;
        }
        else return true;
	};
	return false;
}
	
/**
 * Labels of the selects
 */
function initLabels()
{
    $('#carModel>select').empty().append(createOption('','Select Model'));
    $('#carYear>select').empty().append(createOption('','Select Year'));
    $('#carMake>select').empty().append(createOption('','Select Make'));
}

/**
 * Building list of makes for product search
 */
function buildMakes ()
{
    $.ajax(
            {   url:'/ajax/search/get-make-list/lan/En',
                data:{},
                type:'GET',
                dataType:'json',
                success : function(data) {
                    $('#carMake>select').empty().append(createOption('','Select Make'));
                    for(x in data) {
                        $('#carMake>select').append(createOption(data[x]['id'],data[x]['vehicleMake']));
                    }
                    $('#carYear>select').attr('disabled','disabled');
                    $('#carModel>select').attr('disabled','disabled');
                },
                error : function(xhr) {
                	ErrorMessage(xhr);
                }
            });
}

/**
 * When a make selection happens...
 */
function makeSelection()
{
    $('#carMake>select').bind('change', function() {
        $.ajax(
                {   url:'/ajax/search/get-year-list/lan/En',

                    data:{make:$(this).val()},
                    type:'GET',
                    dataType:'json',
                    success : function(data) {
                        $('#carYear>select').empty().append(createOption('','Select Year'));
                        for(x in data) {
                            $('#carYear>select').append(createOption(data[x]['id'],data[x]['vehicleYear']));
                        }
                        $('#carYear>select').removeAttr('disabled');
                        $('#carModel>select').attr('disabled','disabled');
                    },
                    error : function(xhr) {
                    	ErrorMessage(xhr);
                    }
                });

    });
}

/**
 * When a year selection happens...
 */
function yearSelection()
{
    $('#carYear>select').bind('change', function() {
        $.ajax(
                {   url:'/ajax/search/get-vehicle-list/lan/En',
                    data:{make:$('#carMake>select').val(),year:$(this).val()},
                    type:'GET',
                    dataType:'json',
                    success : function(data) {
                        $('#carModel>select').empty().append(createOption('','Select Model'));
                        for(x in data) {
                            $('#carModel>select').append(createOption(data[x]['id'],data[x]['vehicleName']));
                        }
                        $('#carModel>select').removeAttr('disabled');
                    },
                    error : function(xhr) {
                    	ErrorMessage(xhr);
                    }
                });

    });
}

/**
 * When a model selection happens...
 */
function modelSelection()
{
    $('#carModel>select').bind('change', function() {
        var vehicleID = $(this).val();
        if(vehicleID == "") return;
        if (CheckIfUpdating()) return;        
        var productList = {};

        $.ajax(
                {   url:'/ajax/product/get-vehicle-product-coverage/lan/En/',
                    data:{'model':vehicleID},
                    type:'GET',
                    dataType:'html',
                    success : function(data) {
                		if (!$("#results_box").length)
                		{
                			$("#update_box").attr('id', 'results_box');
                		};                    	
                    	$('#results_box').html(data);
                    	productSearchResult.init();
                    },
                    error : function(xhr) {
                    	ErrorMessage(xhr);
                    }
                });
    });
}

/**
 * Building list of products for product search
 */
function buildProducts()
{
    $.ajax(
            {   url:'/ajax/search/get-product-list/lan/En',
                data:{},
                type:'GET',
                dataType:'json',
                success : function(data) {
                    $('#productSeriesList>select').empty().append(createOption('','Select Product'));
                    for(x in data) {
                        $('#productSeriesList>select').append(createOption(data[x]['id'],data[x]['Name']));
                    }
                },
                error : function(xhr) {
                	ErrorMessage(xhr);
                }
            });
}

/**
 * When a product selection happens in the product search form...
 */
function productSelection()
{
    $('#productSeriesList>select').bind('change', function() {
    	var productID = $(this).val();
        if(productID!="") {
            if (CheckIfUpdating()) return;
            
            detail = new productDetail(productID);
        	detail.getProductDetail();
        }
    });
}

/******************************************************************************
 * Install Guide Search block
 */
function InstallGuidesSearch(path)
{
    buildInstallGuides();
    guideSelection(path);
}

/**
 * Building list of products for install guide search
 */
function buildInstallGuides()
{
    $.ajax(
            {   url:'/ajax/search/get-install-guides-list/lan/En',
                data:{},
                type:'GET',
                dataType:'json',
                success : function(data) {
                    $('#selectGuide>select').empty().append(createOption("",'Select Product'));
                    for(x in data) {
                        $('#selectGuide>select').append(createOption(data[x]['id'],data[x]['Name']));
                    }
                },
                error : function(xhr) {
                	ErrorMessage(xhr);
                }
            });
}

/**
 * When a product selection happens in the install guide search form...
 */
function guideSelection(path)
{
    $('#selectGuide>select').bind('change', function() {
    	if($(this).val()!=""){
            if (CheckIfUpdating()) return;
            
    		location.href=path+$(this).val();
    	}
    });
}

/******************************************************************************
 * Page, injected in the results_box
 */
function Results()
{
    loadResults();
}

/**
 * Loading pages in the results_box
 */
function loadResults()
{
    $(".load_results").live('click', function() {
        if (CheckIfUpdating()) return;

        var actionID = $(this).attr("id");
        var tempArray = actionID.split('_');
        actionID = tempArray.join('-');

        $.ajax({
            url:'/common/index/'+actionID,
            type:'GET',
            dataType:'html',
            success : function(data) {
        		if (!$("#results_box").length)
        		{
        			$("#update_box").attr('id', 'results_box');
        		};
                $("#results_box").html(data);
            },
            error : function(xhr) {
            	ErrorMessage(xhr);
            }
        });
    });
}

/******************************************************************************
 * Install Guides page
 */
function InstallGuidesPage(path)
{
    markInstallGuide()
    unmarkInstallGuide();
    downloadInstallGuide(path);
    prepareGuideCode();
}

/**
 * Marking the install guide items
 */
function markInstallGuide()
{
    $(".install_guide_item").live('mouseover', function() {
    	$(this).toggleClass('highlight');
    });
}

/**
 * Unmarking the install guide items
 */
function unmarkInstallGuide()
{
    $(".install_guide_item").live('mouseout', function() {
    	$(this).toggleClass('highlight');
    });
}

/**
 * Download install guide
 */
function downloadInstallGuide(path)
{
	$('.guide').live('click', function(){
        var firmwareID = $(this).attr("firmwareId");
        var that = $(this);
        $.ajax({
            url:'/common/file/get-install-guide/firmware/'+firmwareID,
            type:'GET',
            dataType:'html',
            success : function(data) {
				MB_bottom.addContent(that.attr("p_name")+" Install Guides",data,function(){
					});
            },
            error : function(xhr) {
            	ErrorMessage(xhr);
            }
        });		
	});				
		
    /**
     * Download install guide when clicking on the string happens
     */
    $(".install_guide_item").live('click', function() {
        if (CheckIfUpdating()) return;
        
        location.href=path+$(this).attr("guideid");
    });

   /**
     * Download install guide when clicking on the "Download" button happens
     */
    $(".download_guide").live('click', function() {
        if (CheckIfUpdating()) return;
        
        var guideid = $(this).siblings("#guideID").children("input").val();
        location.href=path+guideid;
    });
}

/**
 * Clears Guide Code edit when it's used first time
 */
function prepareGuideCode()
{
    $(".guide_code").live('click', function() {
       if ($(this).val()=="Guide Code") $(this).attr("value","");
    });
}

/******************************************************************************
 * Weblink page
 */
function WeblinkPage()
{
   showAnswer();
}

/**
 * Showing and hiding answers in Weblink section
 */
function showAnswer()
{
    $(".question").live('click', function() {
        var qid = $(this).attr("id");
        var aid = 'a'+qid.substring(1);
        if ($("#"+aid).css("display") == "block") $(this).css("font-weight", "normal");
        else $(this).css("font-weight", "bold");
        $("#"+aid).toggle("fast");
    });
}

/**
 * Showing an animation while page is loading
 */
function showLoader()
{
	$('.additional_detail').addClass('loading');
    /*if ($('*').attr('id') != 'loader')
        $('#loader_box').append('<img src="../common/images/animation/loader.gif" id="loader">');*/
}

/**
 * Hiding the animation when page is loaded
 */
function hideLoader()
{
	$('.additional_detail').removeClass('loading');
    //$('#loader').remove();
}