var sJsonServiceUrl = sWebsiteRoot + "system/services/json";
var sNoResultMessage = "Er zijn helaas geen resultaten gevonden die voldoen aan uw zoekopdracht."
var aProductChooserData = [];
var aChoises = [];
var nAnimationSpeed = 500;
var bDebug = false;

$.urlParam = function( sName )
{
    var results = new RegExp( "[\\?&]" + sName + "=([^&#]*)" ).exec( window.location.href );
    return results[ 1 ] || 0;
}

function fetchData( sService, aData )
{
    var mResponse;
    $.ajax
    ({
        async : false,
        type: "POST",
        url: sJsonServiceUrl,
        data :
        {
            "sService" : sService,
            "aData" : aData
        },
        success : function( aResponse )
        {
            mResponse = $.parseJSON( aResponse );
        },
        error : function()
        {
            alert( "An error occurred while trying to fech data." );
        }
    });
    return mResponse;
}

function removeQuestionElements()
{
    $( "#chooserQuestionHolder" ).fadeIn( nAnimationSpeed );
    $( ".chooserSelect" ).remove();
    $( ".chooserOption" ).remove();
    $( "#chooserQuestionHolder" ).find( ".jquery-selectbox" ).remove();
}

function buildChooser()
{
    var sName = aProductChooserData.description;
    $( "#chooserTitle" ).html( sName );
}

function selectOptionClicked( sName, sValue, sAnswer )
{
    var aFilterParts = sValue.split( "_" );
    aChoises.push( {"filter_type" : aFilterParts[ 0 ], "filter_value" : aFilterParts[ 1 ]} );

    var nNextId = aFilterParts[ 2 ];
    
    if ( sName == "" || sValue == "" || sValue == "empty" )
    {
        return;
    }
    var oChoise = $( '<li id="choise_' + sName + '"><strong>' +
        sName + '</strong>' + sAnswer + '<br /></li>' ).fadeIn( nAnimationSpeed );

    oChoise.appendTo( $( "#chooserChoises" ) );

    $( "#chooserQuestionHolder" ).fadeOut( nAnimationSpeed, function()
    {
        removeQuestionElements();
        jump( nNextId );
    });
}

function buildSelectOptions( oQuestion )
{
    var oSelectOption = $( '<select id="' + oQuestion.name + '" class="chooserSelect"></select>' );

    $( '<option value="empty">Maak uw keuze</option>' ).appendTo( oSelectOption );

    $( oQuestion.answers ).each( function()
    {
        var oAnswer = $( this )[ 0 ];
        $( '<option class="chooserOption" name="' + oAnswer.answer + '" value="' + oAnswer.filter_type + "_" + oAnswer.filter_value +
            "_" + oAnswer.next_question_id +
                '">' + oAnswer.answer + '</option>' )
        .appendTo( oSelectOption );

        if ( bDebug )
        {
            console.log( oSelectOption );
        }
    });

    oSelectOption.appendTo( $( "#chooserQuestionHolder" ) );
}

function buildQuestion( nId )
{
    var oQuestion = fetchQuestion( nId );

    if ( oQuestion != null )
    {
        $( "#chooserQuestion" ).html( oQuestion.question );
        $( "#chooserQuestion" ).append( oQuestion.text );

        buildSelectOptions( oQuestion );
    }
}

function fetchQuestion( nId )
{
    var oQuestion = null;
    $( aProductChooserData.questions ).each( function()
    {
        if ( $( this )[ 0 ].id == nId )
        {
            oQuestion = $( this )[ 0 ];
            return false;
        }
    });
    return oQuestion;
}

function jump( nNextId )
{
    // Logic used for unit testing:
    // showResults();
    // return;

    if ( nNextId == "null" || nNextId == "0" )
    {
        $( "#chooserQuestionHolder" ).fadeIn( "fast" );
        $( "#chooserQuestionHolder" ).html( '<img src="' + sWebsiteRoot + 'images/loading.gif" alt="loading" />' );

        setTimeout( showResults, 300 );
    }
    else
    {
        buildQuestion( nNextId );
    }

    // Bind change event
    $( ".chooserSelect" ).selectbox().bind( "change", function()
    {       
        selectOptionClicked( $( this ).attr( "id" ), $( this ).val(),
            $( "select.chooserSelect option:selected" ).text() );
    });
}

function showResults()
{
    var sResultType = aProductChooserData.type;
    var aResultData = fetchData( sResultType + "Result", aChoises );

    // Logic used for unit testing:
    // var aResultData = fetchData( "serieResult", [] );
    // aProductChooserData.type = "serie";

    if ( bDebug )
    {
        console.log( aResultData );
    }

    if ( aResultData == "null" || aResultData =="0" || aResultData == "" )
    {
        $( "#chooserQuestionHolder" ).html( sNoResultMessage );
    }
    else
    {
        var sResult = '<p><strong>Resultaten</strong></p>';

        switch( sResultType )
        {
            case "download" :
                sResult += '<div id="specs"><div>';
                $( aResultData ).each( function()
                {
                    var oData = $( this )[ 0 ];
                    var sDownload = '<h3><a href="#">' + oData.sType + '</a></h3><div>';
                    $( oData.aDownloads ).each( function()
                    {
                        var oDownloadData = $( this )[ 0 ];
                        sDownload += '<p><a href="' + oDownloadData.sUrl + '">' +
                            oDownloadData.sName + '</a></p>';
                    });
                    sDownload += '</div>';
                    sResult += sDownload;
                });
                sResult += "</div></div>";
            break;

            case "serie" :
                sResult += '<ul id="category">';
                $( aResultData ).each( function()
                {
                    var oData = $( this )[ 0 ];
                    sResult += '<li><a href="' + sWebsiteRoot + oData.sLink + '"><img src="' +
                        oData.sImage + '" alt="' + oData.sName + '" />' +
                        oData.sLinkName + '</a></li>';
                });
                sResult += "</ul>";
            break;

            case "support" :
                sResult += '<div id="specs"><div>';
                $( aResultData ).each( function()
                {
                    var oData = $( this )[ 0 ];
                    var sFeature = '<h3><a href="#">' + oData.sType + '</a></h3><div>';
                    $( oData.aFeatures ).each( function()
                    {
                        var oFeatureData = $( this )[ 0 ];
                        sFeature += '<p><a href="' + oFeatureData.sUrl + '">' +
                            oFeatureData.sName + '</a></p>';
                    });
                    sFeature += '</div>';
                    sResult += sFeature;
                });
                sResult += "</div></div>";
            break;
        }

        $( "#chooserQuestionHolder" ).html( sResult );

        if ( bDebug )
        {
            console.log( aResultData );
        }
    }
}

// Perform chooser actions
$( function()
{
    // Set product chooser
    if ( !$( ".productChooser" ).length )
    {
        return;
    }

    var aChooserData = fetchData( "chooser",
    {
        "iId" : $.urlParam( "id" )
    });

    aProductChooserData = aChooserData;
    
    if ( bDebug )
    {    
        console.log( aProductChooserData );
    }

    buildChooser();

    jump( aProductChooserData.questions[ 0 ].id );
});


// Perform other page actions
$( function()
{
    // Set selectmenu's with styling
    /*
    if ( $( "select" ).length )
    {
        $( "select" ).selectbox();
    }
    */

    // Set Accordeons

    if ( $( "#productSupport" ).length )
    {
        $( "#productSupport" ).accordion({
                header: "h3",
                collapsible: true,
                autoHeight: false,
        });
    }

    // Set table sorter
    $( "table" ).tablesorter
    ({
        sortList: [[0,0]],
        widthFixed: true,
        widgets: [ "zebra" ]
    })
    $( "tr:odd" ).addClass( "odd" );
    $( "tr:even" ).addClass( "even" );

    // Bind change event for the jump menu   
    $( "#jumpmenu" ).bind( "change", function()
    {
        window.location.href = sWebsiteRoot + $( this ).val();
    });
    
    $( "#jumpmenu" ).bind( "update", function()
    {
        window.location.href = sWebsiteRoot + $( this ).val();
    });

    $( "#choosermenu" ).bind( "change", function()
    {
        window.location.href = sWebsiteRoot + $( this ).val();
    });

    $( "a" ).each(
        function()
        {
            $( this ).attr( "title", "" );
            $( this ).attr( "alt", "" );
            $( this ).mouseover( function ()
            {
                window.status = "";
                return true;
            })
        })
    //binding the classes to the headers on the functionaliteiten page
    $("div.functionality h3:contains('VoIP')").addClass(function() {
    return this.innerHTML.replace("voip", "VoIP ").toLowerCase();
    });
    $("div.functionality h3:contains('ISDN S0 NT/TE')").addClass(function() {
    return this.innerHTML.replace("ISDN S0 NT/TE", "isdn ").toLowerCase();
    });
    $("div.functionality h3:contains('Anti-virus/Anti-intrusion')").addClass(function() {
    return this.innerHTML.replace("Anti-virus/Anti-intrusion", "anti-virus ").toLowerCase();
    });
    $("div.functionality h3:contains('Anti-Spam')").addClass(function() {
    return this.innerHTML.replace("Anti-Spam", "anti-spam ").toLowerCase();
    });
    $("div.functionality h3:contains('Wireless')").addClass(function() {
    return this.innerHTML.replace("Wireless", "wireless ").toLowerCase();
    });
    $("div.functionality h3:contains('3,5G UMTS/HSDPA')").addClass(function() {
    return this.innerHTML.replace("3,5G UMTS/HSDPA", "umts ").toLowerCase();
    });
    $("div.functionality h3:contains('Multiple WAN/Load balancing')").addClass(function() {
    return this.innerHTML.replace("Multiple WAN/Load balancing", "wan ").toLowerCase();
    });
    $("div.functionality h3:contains('VPN')").addClass(function() {
    return this.innerHTML.replace("VPN", "vpn ").toLowerCase();
    });

    });


/*
$(document).ready(function() {
	// Set selectmenu's with styling
    $("select").selectbox();
});
*/

//
function slideShow(speed) {
	//Set the opacity of all images to 0
	$('ul.slideshow li').css({opacity: 0.0});
	//Get the first image and display it (set it to full opacity)
	$('ul.slideshow li:first').css({opacity: 1.0});
	//Call the gallery function to run the slideshow
	var timer = setInterval('gallery()',speed);
	//pause the slideshow on mouse over
	$('ul.slideshow').hover(
		function () {
			clearInterval(timer);
		},
		function () {
			timer = setInterval('gallery()',speed);
		}
	);
	$('#slider .links .group a').click(
		function () {
			clearInterval(timer);
			timer = setInterval('gallery()',5000);
		}
	);
}

function gallery() {
	//if no IMGs have the show class, grab the first image
	var current = ($('ul.slideshow li.show')?  $('ul.slideshow li.show') : $('#ul.slideshow li:first'));
	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first'));
	//Set the fade in effect for the next image, show class has higher z-index
	next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);
	//Hide the current image
	current.animate({opacity: 0.0}, 1000).removeClass('show');
}




