var gwTellus =
{
    itemClass: 'item',
    itemArray: new Array(),
    itemPointer: new Array(),

    timer: false,
    waitSec: 8,
    transSec: 2,

    tellusUpdateCounter: 0,
    gwGlobalHash: '',

    subCategorySelected: false,

    map_id: 'google-canvas',
    map_height: 300,

    submitCapacityForm: function( id, prefixValue )
    {
        var formList = $('#' + id).serializeArray();
        var urlParamString = '?';
        var tmpValue = '';
        var fromDate = '';
        var toDate = '';
        for ( i in formList )
        {
            if ( formList[i].name == 'fromDate' )
            {
                tmpValue = formList[i].value.split( '.' );
                urlParamString += formList[i].name + '=' + tmpValue[2] + tmpValue[1] + tmpValue[0] + '&';
            }
            else if ( formList[i].name == 'toDate' )
            {
                tmpValue = $('#' + prefixValue + 'capacity-from-id' ).val().split( '.' );
                fromDate = new Date( parseInt( tmpValue[2]), parseInt(tmpValue[1]) - 1, parseInt( tmpValue[0] ), 0, 0, 0 );

                tmpValue = $('#' + prefixValue + 'capacity-to-id' ).val().split( '.' );
                toDate = new Date( parseInt( tmpValue[2]), parseInt(tmpValue[1]) - 1, parseInt( tmpValue[0] ), 0, 0, 0 );

                tmpValue = parseInt( ( toDate.getTime() - fromDate.getTime() ) / 1000 / 24 / 60 / 60 );
                urlParamString += 'nights=' + tmpValue + '&';
            }
            else
            {
                urlParamString += formList[i].name + '=' + formList[i].value + '&';
            }
        }

        var redirectURL = $('#' + id).attr( 'action' ) + urlParamString.replace( /\s|\&$/, '' );
        secondWin = open( redirectURL, 'Online booking', 'heigh=auto,width=auto,scrollbars=yes,menubar=yes,status=no,location=no,titlebar=no,toolbar=no' );
        return false;
    },

    submitGuestmakerCapacityForm: function( id, prefixValue )
    {
        var formList = $('#' + id).serializeArray();
        var urlParamString = '?';
        var mode = $('#' + prefixValue + 'mode').val();
        var tmpValue = '';
        var producttypeStr = '';
        var producttype = '';
        var nights = '';
        var roomsStr = '';
        if ( id == prefixValue + 'submit-activities-form' )
        {
            var fromDate = $('#' + prefixValue + 'capacity-act-from-id' ).val();
            var toDate =   $('#' + prefixValue + 'capacity-act-to-id' ).val();
            var languageCode = $('#' + prefixValue + 'culture-act' ).val();

            // From date
            tmpValue = fromDate.split( '.' );
            urlParamString += 'fromdate=' + tmpValue[2] + tmpValue[1] + tmpValue[0] + '&';

            // To date
            tmpValue = toDate.split( '.' );
            urlParamString += 'todate=' + tmpValue[2] + tmpValue[1] + tmpValue[0];

            // language code
            urlParamString += 'culture=' + languageCode;
        }
        else
        {
            $( 'input[name="' + prefixValue + 'producttype[]"]:checked' ).each( function() {

                 if ( producttypeStr != '' )
                 {
                     producttypeStr += '-';
                 }
                 producttypeStr += $(this).val();

            } );

            var fromDate = $('#' + prefixValue + 'capacity-from-id' ).val();
            var toDate =   $('#' + prefixValue + 'capacity-to-id' ).val();

            // From date
            tmpValue = fromDate.split( '.' );
            urlParamString += 'fromdate=' + tmpValue[2] + tmpValue[1] + tmpValue[0] + '&';

            // To date
            tmpValue = $('#' + prefixValue + 'capacity-from-id' ).val().split( '.' );
            fromDate = new Date( parseInt( tmpValue[2]), parseInt(tmpValue[1]) - 1, parseInt( tmpValue[0] ), 0, 0, 0 );

            tmpValue = $('#' + prefixValue + 'capacity-to-id' ).val().split( '.' );
            toDate = new Date( parseInt( tmpValue[2]), parseInt(tmpValue[1]) - 1, parseInt( tmpValue[0] ), 0, 0, 0 );

            nights = parseInt( ( toDate.getTime() - fromDate.getTime() ) / 1000 / 24 / 60 / 60 );

            // mode
            urlParamString += 'nights=' + nights + '&mode=' + mode + '&';

            // producttype
            urlParamString += 'producttypes=' + producttypeStr + '&';

            var persons = '';
            var children = '';
            var childCount = '';
            var childCountStr = '';
            // rooms
            for ( i=1; i <= $('#' + prefixValue + 'rooms' ).val(); i++ )
            {
                if ( document.getElementById( prefixValue + 'persons-' + i ) != undefined &&
                     document.getElementById( prefixValue + 'children-' + i ) != undefined )
                {
                    persons = $('#' + prefixValue + 'persons-' + i ).val();
                    children = $('#' + prefixValue + 'children-' + i ).val();
                    childCountStr = '';
                    if ( children > 0 )
                    {
                        for ( subi=1; subi <= children; subi++ )
                        {
                            if ( document.getElementById( prefixValue + 'child-age-' + i + '-' + subi ) != undefined )
                            {
                                childCount = $('#' + prefixValue + 'child-age-' + i + '-' + subi ).val();
                                if ( childCountStr != '' )
                                {
                                    childCountStr += '_';
                                }
                                childCountStr += childCount;
                            }
                        }
                    }
                    if ( i != $('#' + prefixValue + 'rooms' ).val() )
                    {
                        childCountStr += '.';
                    }
                    roomsStr += i + '-' + persons + '-' + children + '-' + childCountStr;
                }

            }
            urlParamString += 'rooms=' + roomsStr;
        }
        var redirectURL = $('#' + id).attr( 'action' ) + urlParamString.replace( /\s|\&$/, '' );
        return redirectURL;
    },

    updatePeopleBlock: function( el, id )
    {
        var value = $(el).val();
        for ( i=1; i<=4; i++ )
        {
            if ( value >= i )
            {
                $('#' + id + i ).removeClass( 'hide' );
            }
            else
            {
                $('#' + id + i ).addClass( 'hide' );
            }
        }
    },

    updateChildrenAge: function( el, id )
    {
        var value = $(el).val();
        for ( i=1; i<=10; i++ )
        {
            if ( value >= i )
            {
                $('#' + id + i ).removeClass( 'hide' );
            }
            else
            {
                $('#' + id + i ).addClass( 'hide' );
            }
        }
    },

    updateCapacityField: function( currentElement, compareElementId, mode )
    {
        var currentArray = $(currentElement).val().split( '.' );
        var currentDateValue = new Date( parseInt( currentArray[2].replace( /^0+/, '' )), parseInt(currentArray[1].replace( /^0+/, '' )) - 1, parseInt( currentArray[0].replace( /^0+/, '' ) ), 0, 0, 0 );

        var compareArray = $('#' + compareElementId).val().split( '.' );
        var compareDateValue = new Date( parseInt( compareArray[2].replace( /^0+/, '' )), parseInt(compareArray[1].replace( /^0+/, '' )) - 1, parseInt( compareArray[0].replace( /^0+/, '' ) ), 0, 0, 0 );


        if ( mode == 'from' && currentDateValue.getTime() >= compareDateValue.getTime() )
        {
            var currentTimeValue = parseInt( currentDateValue.getTime() ) + 86400000;
            var monthValue = parseInt( currentDateValue.getMonth() );
            monthValue += 1;
            currentDateValue.setTime( currentTimeValue );
            $('#' + compareElementId).val( this.padNumber( currentDateValue.getDate() ) + '.' + this.padNumber( currentDateValue.getMonth() + 1 ) + '.' + currentDateValue.getFullYear() );
        }
        else if ( mode == 'to' && currentDateValue.getTime() <= compareDateValue.getTime() )
        {
            var currentTimeValue = parseInt( currentDateValue.getTime() ) - 86400000;
            var monthValue = parseInt( currentDateValue.getMonth() );
            monthValue += 1;
            currentDateValue.setTime( currentTimeValue );
            $('#' + compareElementId).val( this.padNumber( currentDateValue.getDate() ) + '.' + this.padNumber( monthValue ) + '.' + currentDateValue.getFullYear() );
        }
    },

    padNumber: function( value )
    {
        if ( value < 10 )
        {
            value = '0' + value;
        }
        return value;
    },

    formatTitle: function(title, currentArray, currentIndex, currentOpts)
    {
        var indexTitle = '';
        if ( currentArray.length > 1 )
        {
            indexTitle =  ' Bilde ' + (currentIndex + 1) + ' av ' + currentArray.length
        }
	    return '<div id="tellus-fancybox-title">' + (title && title.length ? '<b>' + title + '</b>' : '' ) + indexTitle + '</div>';
     },

    addFacebookComments: function( href )
    {
        document.write( '<fb:comments numposts="20" width="450px" href="' + href + '"></fb:comments>' );
    },

    tellusImageGallery: function( name, title )
    {
		$("." + name).fancybox(
        {
			//'orig'			: $(this),
			'padding'		: 2,
			'title'   		: $(this).title,
     		'titlePosition' : 'inside',
            'titleFormat'		: this.formatTitle,
			'transitionIn'	: 'easeOutBack',
            'transitionOut'	: 'easeOutBack'
		});
    },

    toggleCheckboxSelection: function( name, type )
    {
        var status = false;
        $("input[class=" + name + "]").each( function( i, e )
        {
            if ( e.type == 'checkbox' )
            {
                if ( e.checked == 0 )
                {
                    status = true;
                }
            }
        } );

        $("input[class=" + name + "]" ).each( function( i, e )
        {
            if ( e.type == 'checkbox' )
            {
                if ( status == true )
                {
                    e.checked = 1;
                }
                else
                {
                    e.checked = 0;
                }
            }
        } );
        this.gwAjaxUpdateForm( false, type );
        return false;
    },


    gwHandleFilterSelectorURL: function( type )
    {
        $('productlist-update-button').css( "display", 'none' );
        var tellusValue = window.location.hash.substring( 1 );
        this.gwGlobalHash = tellusValue;
        var newValue = '';
        var tellusAction = '';
        if ( tellusValue != '' )
        {
            var tellusArray = tellusValue.split( "&" );

            var tellusSubCategories = '';
            var tellusDB = '';
            var tellusLimit = 10;

            var tellusSubCategoriesFound = false;
            var tellusDBFound = false;
            var tellusLimitFound = false;

            var name = '';
            $.each( tellusArray, function ( i, value )
            {
                var tempValue = value.split( '=' );
                $.each( tempValue, function ( subI, newValue )
                {
                    if ( name == 'tlcc' )
                        {
                            tellusSubCategories = newValue;
                            tellusSubCategoriesFound = true;
                        }
                    else if ( name == 'tldb' )
                        {
                            tellusDB = newValue;
                            tellusDBFound = true;
                        }
                    else if ( name == 'tlll' )
                        {
                            tellusLimit = newValue;
                            tellusLimitFound = true;
                        }

                    name = '';
                    if ( newValue == 'tlcc' )
                        {
                            name = 'tlcc';
                        }
                        else if ( newValue == 'tldb' )
                            {
                                name = 'tldb';
                            }
                        else if ( newValue == 'tlll' )
                            {
                                name = 'tlll';
                            }

                    } );
            } );
            if ( tellusLimitFound == true &&
                 tellusDBFound == true &&
                 tellusLimitFound == true )
                {
                    this.gwUpdateTellusCheckedValue( 'tellus-sub-category', tellusSubCategories );
                    this.gwUpdateTellusCheckedValue( 'tellus-destination', tellusDB );
                    this.gwUpdateTellusLimitValue( 'productlist-limit', tellusLimit );

                    this.gwAjaxUpdateForm( true, type );
                }
        }
    },

    gwIntervalTest: function( type )
    {
        var tellusValue = window.location.hash.substring( 1 );

        if ( tellusValue != this.gwGlobalHash )
        {
            gwTellus.gwHandleFilterSelectorURL( type );
        }
    },

    gwUpdateTellusLimitValue: function( name, value )
    {
        $('#' + name).val( value );
        return $('#' + name).val()
    },

    gwTellusLimitValue: function( name )
    {
        if ( $('#' + name).val != undefined )
            return $('#' + name).val();
        return '';
    },

    gwUpdateTellusCheckedValue: function( className, values )
    {
        $('.' + className).each( function ( i, e )
        {
            if ( e.checked == 1 )
            {
                e.checked = 1;
            }
            else
            {
                e.checked = 0;
            }
        } );
    },

    gwUpdateTellusInputValues: function( className )
    {
        var isAdded = false;
        var value = '';
        $('.' + className).each( function( i, e ) {
            if ( e.checked )
            {
               if ( isAdded == true )
                   value += ',';
               else
                   isAdded = true;

               value += e.value;
            } } );
        return value;
    },

    incTellusCounter: function()
    {
        this.tellusUpdateCounter++;
        $("input[name=tellus_counter]").val( this.tellusUpdateCounter );
    },

    registerSubCategory: function()
    {
        this.subCategorySelected = true;
    },

    /* ajax product list */
    gwAjaxUpdateForm: function( doNotUpdateHash, type )
    {
        var language = gwSiteLanguage;
        if ( language != '' )
        {
            language = '/' + language;
        }

        if ( this.subCategorySelected == false )
        {
            this.subCategorySelected = true;
            this.toggleCheckboxSelection( 'tellus-sub-category', type );
        }
        else
        {
            var url =  language + '/tellus/ajax/' + type;
            var value = 'tlcc=' + this.gwUpdateTellusInputValues( 'tellus-sub-category' ) +
            '&tldb=' + this.gwUpdateTellusInputValues( 'tellus-destination' ) +
            '&tlll=' + this.gwTellusLimitValue( 'productlist-limit' );

            this.incTellusCounter();
            if ( doNotUpdateHash == undefined || doNotUpdateHash == false  )
            {
                location.href = '#' + value;
            }
            this.gwGlobalHash = value;

            var params = $("#tellus-filter").serialize();

            $.ajax({
            requestCounter: 0,
            type: "POST",
             beforeSend: function( html ) {gwTellus.updateTellusProductListLoading();},
             url: url,
             data: params,
             cache: false,
             dataType: 'json',
             success: function( jsonArray ){gwTellus.updateTellusContentSuccess( jsonArray );}
        });
        }
        return false;
    },

    updateTellusProductListLoading: function()
    {
        $('#update-tellus-loading').css( "display", "inline" );

        $('#productlist-invert-button').css( "color", "#a0a0a0" );
        $('#productlist-invert-button').disabled = true;

        $('#productlist-update-button').css( "color", "#a0a0a0" );
        $('#productlist-update-button').disabled = true;

        $('#page').css( 'cursor', 'progress' );
        $('.filter-selector-options').css( 'cursor', 'progress' );
        $('input').css( 'cursor', 'progress' );
        $('label').css( 'cursor', 'progress' );
        $('div').css( 'cursor', 'progress' );

        this.requestCounter = gwTellus.tellusUpdateCounter;
    },

    updateTellusContentSuccess: function( jsonArray )
    {
        if ( jsonArray.tellus_counter == gwTellus.tellusUpdateCounter )
        {
            $('#update-tellus-loading').css( "display", "none" );
            $('#tellus-product-list').html( jsonArray.tellus_content );
            var map_id = gwTellus.map_id;
            var map_height = gwTellus.map_height;
            var map = document.getElementById( map_id );
            if ( map )
            {
                gwGMarkerMap.setHeight( map_id, map_height );

                gwGMarkerMap.initialize( map_id );
                gwGMarkerMap.addAllMarkers();
                gwGMarkerMap.zoomToFit();
            }

            $('#productlist-invert-button').css( "color", "#000000" );
            $('#productlist-invert-button').disabled = false;

            $('#productlist-update-button').css( "color", "#000000" );
            $('#productlist-update-button').disabled = false;

            $('#page').css( 'cursor', 'default' );
            $('.filter-selector-options').css( 'cursor', 'default' );
            $('input').css( 'cursor', 'default' );
            $('label').css( 'cursor', 'default' );
            $('div').css( 'cursor', 'default' );
            $('.filter-selector-options').css( 'cursor', 'default' );
        }
    },

    updateDatepicker: function( fromId, toId )
    {
        var currentDate = $("#" + fromId ).datepicker( 'getDate' );
        $( "#" + toId ).datepicker( 'option', 'minDate', currentDate );
    }

}

