/* 
 * GeoLocationValidation
 * Determins if user is in correct store.
 * @author Yining Zhao
 */
jQuery(document).ready(function(){
    GeoLocationValidation.init();
});
var GeoLocationValidation = function(){
    var _widgetContext;
    var _clientLocationName;
    var _properStoreCode;
    var _currentStoreCode;
    var _disablePopup = false;
    var _numDaysTillCookieExpiration = 1;//30;
    var _numDaysTillCountryCodeCookieExpiration = 30;//1;
    var _geoLocationEstablishedCookieName = 'SKULLCANDY_GEOLOCATION_ESTABLISHED';
    var _countryCodeCookieName = 'SKULLCANDY_GEOLOCATION_COUNTRYCODE'
    var _getClientGeoInfo = function(){
        var ipLookupServiceUrl;
        var countryCodeFound;
        if(countryCode = _getCookie(_countryCodeCookieName)){
            _setClientInfoFromCountryCode(countryCode);
            _validateAppropriateSite();
        } else {
            ipLookupServiceUrl = '/geoLocationValidationGetIp.php';
            jQuery.post(ipLookupServiceUrl, function(countryCode){
                countryCodeFound = _setClientInfoFromCountryCode(countryCode);
                if(countryCodeFound){
                    _setCookie( _countryCodeCookieName, countryCode, _numDaysTillCountryCodeCookieExpiration, '/', 'skullcandy.com', '' );
                }
                _validateAppropriateSite();
            });
        }

    };
    var _setClientInfoFromCountryCode = function(countryCode){
        var countryCodeFound = true;
        switch(countryCode){
            case 'AT'://Austria
                _clientLocationName = 'Austria';
                _properStoreCode = 'eu';
                break;
            case 'BE'://Belgium
                _clientLocationName = 'Belgium';
                _properStoreCode = 'eu';
                break;
            case 'BG'://Bulgaria
                _clientLocationName = 'Bulgaria';
                _properStoreCode = 'eu';
                break;
            case 'CY'://Cyprus
                _clientLocationName = 'Cyprus';
                _properStoreCode = 'eu';
                break;
            case 'CZ'://Czech Republic
                _clientLocationName = 'Czech Republic';
                _properStoreCode = 'eu';
                break;
            case 'DK'://Denmark
                _clientLocationName = 'Denmark';
                _properStoreCode = 'eu';
                break;
            case 'EE'://Estonia
                _clientLocationName = 'Estonia';
                _properStoreCode = 'eu';
                break;
            case 'FI'://Finland
                _clientLocationName = 'Finland';
                _properStoreCode = 'eu';
                break;
            case 'FR'://France
                _clientLocationName = 'France';
                _properStoreCode = 'eu';
                break;
            case 'DE'://Germany
                _clientLocationName = 'Germany';
                _properStoreCode = 'eu';
                break;
            case 'GR'://Greece
                _clientLocationName = 'Greece';
                _properStoreCode = 'eu';
                break;
            case 'HU'://Hungary
                _clientLocationName = 'Hungary';
                _properStoreCode = 'eu';
                break;
            case 'IE'://Ireland
                _clientLocationName = 'Ireland';
                _properStoreCode = 'eu';
                break;
            case 'IT'://Italy
                _clientLocationName = 'Italy';
                _properStoreCode = 'eu';
                break;
            case 'LV'://Latvia
                _clientLocationName = 'Latvia';
                _properStoreCode = 'eu';
                break;
            case 'LT'://Lithuania
                _clientLocationName = 'Lithuania';
                _properStoreCode = 'eu';
                break;
            case 'LU'://Luxembourg
                _clientLocationName = 'Luxembourg';
                _properStoreCode = 'eu';
                break;
            case 'MT'://Malta
                _clientLocationName = 'Malta';
                _properStoreCode = 'eu';
                break;
            case 'NL'://Netherlands
                _clientLocationName = 'Netherlands';
                _properStoreCode = 'eu';
                break;
            case 'PL'://Poland
                _clientLocationName = 'Poland';
                _properStoreCode = 'eu';
                break;
            case 'PT'://Portugal
                _clientLocationName = 'Portugal';
                _properStoreCode = 'eu';
                break;
            case 'RO'://Romania
                _clientLocationName = 'Romania';
                _properStoreCode = 'eu';
                break;
            case 'SK'://Slovakia
                _clientLocationName = 'Slovakia';
                _properStoreCode = 'eu';
                break;
            case 'SI'://Slovenia
                _clientLocationName = 'Slovenia';
                _properStoreCode = 'eu';
                break;
            case 'ES'://Spain
                _clientLocationName = 'Spain';
                _properStoreCode = 'eu';
                break;
            case 'SE'://Sweden
                _clientLocationName = 'Sweden';
                _properStoreCode = 'eu';
                break;
                break;
            case 'GB'://United Kingdom
            case 'UK':
                _clientLocationName = 'United Kingdom';
                _properStoreCode = 'uk';
                break;
            case 'US'://US
                _clientLocationName = 'United States';
                _properStoreCode = 'us';
                break;
            default://For other countries we don't do anything
                _disablePopup = true;
                countryCodeFound = false;
        }
        return countryCodeFound;
    };
    var _getStoreInfoFromCode = function(storeCode){
        var storeName, storeUrl, storeInfo;
        switch(storeCode){
            case 'eu':
                storeName = "Skullcandy EU Store";
                storeUrl = 'http://eu.skullcandy.com';
                break;
            case 'uk':
                storeName = "Skullcandy UK Store";
                storeUrl = 'http://uk.skullcandy.com';
                break;
            case 'us':
                storeName = "Skullcandy US Store";
                storeUrl = 'http://www.skullcandy.com';
                break;
        }
        storeInfo = {
            storeName: storeName,
            storeUrl: storeUrl
        }
        return storeInfo;
    };
    var _getCurrentStoreInfo = function(){
        var currentStoreDomain = document.location.hostname;
        switch(currentStoreDomain){
            case 'eu.skullcandy.com':
            case 'www.skullcandy.eu':
                _currentStoreCode = 'eu';
                break;
            case 'uk.skullcandy.com':
            case 'www.skullcandy.uk':
                _currentStoreCode = 'uk';
                break;
            default:
                _currentStoreCode = 'us';
        }
    };
    var _validateAppropriateSite = function(){
        
        _getCurrentStoreInfo();
        if(_disablePopup){
            return false;
        }
        if(_currentStoreCode != _properStoreCode){
			_gotoProperStore();
            //_showMessageToVisitProperStore();
        }
    };
    var _showMessageToVisitProperStore = function(){
        var messageBoxContext = _getMessageBox();
        var properStoreInfo = _getStoreInfoFromCode(_properStoreCode);
        var bodyWidth = jQuery('BODY').width();
        var messageBoxWidth = messageBoxContext.width();
        var messageBoxLeftMargin = 0.5 * bodyWidth - 0.5 * messageBoxWidth;

        messageBoxContext.find('.clientLocationName').text(_clientLocationName);
        messageBoxContext.find('.shopName').text(properStoreInfo.storeName);
        messageBoxContext.css({left: messageBoxLeftMargin}).show();
        _setCookie( _geoLocationEstablishedCookieName, true, _numDaysTillCookieExpiration, '/', 'skullcandy.com', '' );
    };
    var _gotoProperStore = function(){
        var properStoreInfo = _getStoreInfoFromCode(_properStoreCode);
        var properStoreUrl = properStoreInfo.storeUrl + document.location.pathname;
        document.location.href = properStoreUrl;
    };
    var _getWidgetContext = function(){
        return _widgetContext;
    };
    var _getMessageBox = function(){
        return _getWidgetContext().find('.messageBox');
    }
    var _attachHandlers = function(){
        _getMessageBox().find('.gotoRecommendedStore, .messageContent .shopName').click(function(){
            _gotoProperStore();
            _getMessageBox().hide();
            return false;
        });
        _getMessageBox().find('.closeBox, .stayAtCurrentStore').click(function(){
            _getMessageBox().hide();
            return false;
        });
    };
    var _setCookie = function( name, value, expires, path, domain, secure )
    {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );

        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
        if ( expires )
        {
        expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
    }
    // this fixes an issue with the old method, ambiguous values
    // with this test document.cookie.indexOf( name + "=" );
    var _getCookie = function ( check_name ) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
                // now we'll split apart each name=value pair
                a_temp_cookie = a_all_cookies[i].split( '=' );


                // and trim left/right whitespace while we're at it
                cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

                // if the extracted name matches passed check_name
                if ( cookie_name == check_name )
                {
                        b_cookie_found = true;
                        // we need to handle case where cookie has no value but exists (no = sign, that is):
                        if ( a_temp_cookie.length > 1 )
                        {
                                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                        }
                        // note that in cases where cookie is initialized but no value, null is returned
                        return cookie_value;
                        break;
                }
                a_temp_cookie = null;
                cookie_name = '';
        }
        if ( !b_cookie_found )
        {
                return null;
        }
    }
    return {
        init : function(){
            //var geoLocationEstablished = Boolean(_getCookie(_geoLocationEstablishedCookieName));
            
			//Only perform geolocation check when on homepage
			if(document.location.pathname != '/'){
				return false;
			}
            
            //if(geoLocationEstablished){
                //If we are in the shop folder, everything is cached, so we can't
                //use ip to determin users origins
                //return false;
            //}
            //Continue with code with we are not in shop folder
            _widgetContext = jQuery('#GeoLocationValidation');
            //_attachHandlers();
            _getClientGeoInfo();
            
        }
    }
}();

