/* 
 * All javascript FUNCTIONS here.
 * Create a separate javascript file for actual execution of functions!
 */

/**
 * Does an ajax request based on value passed in to return a list of all matches
 *
 * @dependencies jQuery
 * @parameter string searchText
 * @parameter string size Determines the layout of the drop down that appears 'large' or 'compact'
 */
function livePhoneSearch(searchText, size)
{
    //Continue only if 3 or more characters have been entered AND we are in the hotel location search
    if( searchText.length >= 3 )
    {
        // Do ajax call to get hotels based on search text, use data to populate suggestions div
        $.getJSON('/script/ajaxCalls.php',{action: 'liveSearch', search: searchText}, function(data){

            var list = '';

            if( data == false )
                list += '<p>No Phones Found</p>';
            else{
                for( var i = 0; i < data.length; i++ )
                {
                    switch(size)
                    {
                        case 'large':
                            list += '<a [[class]] href="/sell/[[makeurl]]/[[modelurl]]/">';
                            list += '   <img src="[[image]]" alt="">';
                            list += '   <div class="left">';
                            list += '       <span>[[make]]</span><p>[[model]]</p>';
                            list += '   </div>';
                            list += '   <div class="right">';
                            list += '   <span>Best price found:</span><p>&pound;[[price]]</p><span><b>[[count]]</b> Prices compared</span>';
                            list += '   </div>';
                            list += '</a>';
                            break;
                        default:
                            list += '<a [[class]] href="/sell/[[makeurl]]/[[modelurl]]/">';
                            list += '    [[make]] [[model]]';
                            list += '</a>';
                            break;
                    }

                    //replace placeholders
                    list = list.replace( '[[makeurl]]', data[i].make.replace(/\s/g, '-') );
                    list = list.replace( '[[modelurl]]', data[i].model.replace(/\s/g, '-') );
                    list = list.replace( '[[make]]', data[i].make );
                    list = list.replace( '[[model]]', data[i].model );
                    list = list.replace( '[[price]]', data[i].hiPrice );
                    list = list.replace( '[[count]]', data[i].totalPrices );
                    list = list.replace( '[[image]]', data[i].image );

                    //Odd row gets different colour bg
                    if( i % 2 != 0 )
                        list = list.replace( '[[class]]', 'class="oddRow"' );
                    else
                        list = list.replace( '[[class]]', '' );
                }
            }

            $('#suggests').html(list);
        })

        //unhide suggestions box
        $('#suggests').fadeIn(400);

    }
    else{
        $('#suggests').html('No Phones Found');
        //hide suggestions box
        $('#suggests').fadeOut(400);
    }
}

/**
 * Does an ajax request based on the make passed in to return a list of models
 *
 * @dependencies jQuery
 * @parameter int make
 */
function getModels(make)
{
    $.getJSON('/script/ajaxCalls.php', {action: 'getModels', make: make}, function(data){
        if(data)
        {
            var option = '';
            for( var i = 0; i < data.length; i++ )
            {
                option += '<option>[[model]]</option>';

                option = option.replace('[[model]]', data[i].model);
            }

            $('#selectModel').html(option);
        }
        else{
            $('#selectModel').html('<option>Sorry, no phones found</option>');
        }
    })
}

/**
 * Checks whether search text field is empty
 *
 * @dependencies jQuery
 * @parameter element The dom element to check
 */
function checkSearch(element)
{
    if( $(element).val().length < 1 || $(element).val() == 'Enter your phone name' )
    {
        alert('Please enter a phone name.');
        return false;
    }
    else{
        var gwoTracker=_gat._getTracker("UA-230706-6");
        gwoTracker._trackPageview("/3961380539/goal");
        return true;
    }
}

/**
 * Checks whether a phone model has been selected when submiting search.
 *
 * @dependencies jQuery
 */
function checkDropDowns()
{
    if( jQuery.trim($('#selectModel').html()) == '<option>Select a Make First</option>' )
    {
        alert('Please Select a Phone Model');
        return false;
    }
    else if( jQuery.trim($('#selectModel').html()) == '<option>Sorry, no phones found</option>' )
    {
        alert('Sorry, there are currently no phones found under this brand.');
        return false;
    }
    else{
        return true;
    }
}

//Across ALL pages - check for A8ID= in url to set cookie, require jquery cookie plugin
function getParameterURL(name){
/*-------------------------------------
Description:
Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
GetParameterFromURL('msg') will get 'hello'
Author: http://www.netlobo.com/url_query_string_javascript.html
Dependencies:
Updates:
@Parameters: name = name of the parameter to extract
-------------------------------------*/
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

if( getParameterURL("A8ID") )
    // if A8ID is set in the URL set value into cookie
    $.cookie('A8ID',getParameterURL("A8ID"),{path: '/', expires: 30})
