var $host = 'http://3m-gsc.co.uk/wrapyourcurves/';

(function($){
    $.fn.pause = function(duration, func){
        $(this).animate({
            dummy: 1
        }, duration, 'swing', func);
        return this;
    };
    $.fn.alert = function(msg, _class, fadeOut){
		$(this).html(msg);
        $(this).addClass(_class);
        $(this).fadeIn("slow");
		if (fadeOut) {
            $(this).pause(5000).fadeOut();
        }
        return this;
    };

    $('#mproWrapper #mproContainer, #thecontactform').css('height', 'auto');
    $('#thecontactform').css('overflow', 'visible');
    $('#thecontactform').css('padding', '0 20px 20px 10px');
	
    $.fn.findDealers = function(type, title, postcode, radius, unit, action){
        var $owner = $(this);
        $.getJSON($host+'php/process.php?action=' + action+'&noauth=1&jsoncallback=?', {type: type, postcode: postcode, radius: radius}, function(response){
			$owner.html('');
            if (response != null) {
                $owner.prepend('<h2>' + title + '</h2>');
            }
			if (type == 'lvw') {
				$('#result_message').html('<p>Your query generated <strong>' + (response ? response.length : 0) + (radius == '99999' ? ' results</strong>' : ' local results</strong> within ' + radius + ' <strong>miles</strong> of <strong>' + postcode + '</strong>') + '. You can try expanding the distance to increase the number of results displayed.</p>');
			}
            if (response != null) {
				$owner.show();
				$owner.append('<div class="dealer_container">');
                $.each(response, function(i, dealer){
					$dealer = '<div style="display: block;" class="dealer row' + i + ' hidden">';
					$dealer += '<h3>' + dealer.name + '</h3>';
					if (dealer.distance && dealer.account_type != 'scotchprint' && dealer.account_type != 'mcs') {
					    $dealer += '<span class="distance" style="font-style:italic;">' + parseInt(dealer.distance).toFixed(2) + ' miles from your postcode</span><p></p>';
					}
					if (dealer.account_type != 'scotchprint') {
					$dealer += '<p>';
					$dealer += dealer.address_line_1 ? dealer.address_line_1 : '';
                    $dealer += dealer.address_line_2 ? ', ' + dealer.address_line_2 : '';
                    $dealer += dealer.town ? ', ' + dealer.town : '';
                    $dealer += dealer.city ? ', ' + dealer.city : '';
					$dealer += dealer.postcode ? ', ' + dealer.postcode : '';
					$dealer += '<p>';
					}
					$dealer += dealer.telephone ? '<p>' + dealer.telephone + '</p>' : '';
					$dealer += (dealer.web ? '<p><a class="external" target="_blank" href="' + dealer.web + '">Visit Website</a></p>' : '');
					$dealer += (dealer.email ? '<p><a class="external" target="_blank" href="mailto:' + dealer.email + '">Send Email</a></p>' : '')
					$dealer += '<p style="margin-bottom:10px;">&nbsp</p>';
					$dealer += '</div>';
					
                    $owner.find('.dealer_container').append($dealer);
                    $owner.find('.dealer_container').find('.row' + i).fadeIn('slow');
                });
				if (type == 'lvw') {
					$paginator = '<div class="dealer_paginator"><div style="float:left;" class="navoptions"><a class="action" href="#" rel="first">first</a> | <a class="action" href="#" rel="prev">prev</a> (<span id="count2"></span> / <span id="total2"></span>) <a class="action" href="#" rel="next">next</a> | <a class="action" href="#" rel="last"> last </a></div><div style="float:right;" class="selperpage">show :<select name="perpage"><option value="5">5 per page</option><option value="10">10 per page</option><option value="15">15 per page</option><option value="20">20 per page</option><option value="25">25 per page</option></select></div></div>';
                    var wrap = $owner.find('.dealer_container');
					wrap.before($paginator);
					wrap.after($paginator);
                    $('.dealer_paginator').find('.action').click(function(){
                        var action = $(this).attr('rel'); // get the appropriate action from the rel attribute
						wrap.trigger(action + '.evtpaginate');
                        return false;
                    });
                    $('.dealer_paginator').find('select[name=perpage]').change(function(){
                        wrap.trigger('refresh.evtpaginate', {perPage: $(this).val()});
                        return false;
                    });
                    wrap.bind('initialized.evtpaginate', function(e, startnum, totalnum){
                        $('.dealer_paginator').find('#count2').text(startnum);
                        $('.dealer_paginator').find('#total2').text(totalnum);
                    });
                    wrap.bind('finished.evtpaginate', function(e, num, isFirst, isLast){$('.dealer_paginator').find('#count2').text(num);});
                    wrap.evtpaginate({perPage: 5});
				}
            }
        });
		
        return this;
    };
    
    $(".default").focus(function(){
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass("blurred");
            $(this).val("");
        }
    });
    $(".default").blur(function(){
        if ($(this).val() == "") {
            $(this).addClass("blurred");
            $(this).val($(this)[0].title);
        }
        else 
            if ($(this).val() == $(this)[0].title) {
                $(this).addClass("blurred");
            }
    });
    $(".default").blur();
		
	$("#gallery").click(function(){
		resetLanding();
		$.getJSON($host+'php/process.php?action=gallery&noauth=1&jsoncallback=?', function(response){
			$('#result_message').html(response);
			$('#result_message').find("a[rel^='prettyPhoto']").prettyPhoto({
                animationSpeed: 'normal', /* fast/slow/normal */
                padding: 40, /* padding for each side of the picture */
                opacity: 0.7, /* Value betwee 0 and 1 */
                showTitle: true, /* true/false */
                allowresize: true, /* true/false */
                counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
                theme: 'dark_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
                modal: true, /* If set to true, only the close button will close the window */
                changepicturecallback: function(){
                }, /* Called everytime an item is shown/changed */
                callback: function(){
                } /* Called when prettyPhoto is closed */
            });
		});
		return false;
	});
	
    $("#buttongo").click(function(){
		resetLanding();
		
        if (($('#postcode_form #postcode').val() == '') || ($('#postcode_form #postcode').val() == $('#postcode_form #postcode').attr('title'))) {
            $('#result_message').alert('<p>Please enter a postcode.</p>', 'error', false);
        } else {
            $('#lvw-results').findDealers('lvw', '3M Local Vehicle Wrappers', $('#postcode').val(), $('#radius').val(), $('#unit').val(), 'psearch');
            $('#mcs-results').findDealers('mcs', '3M Regional Partners - MCS', $('#postcode').val(), $('#radius').val(), $('#unit').val(), 'psearch');
            $('#scotchprint-results').findDealers('scotchprint', '3M National Partners - Scotchprint', '', '', '', 'tsearch');
			$('#sponsored-results').show('slow');
        }
		
        return false;
    });
	
	$('#logout').click(function(){
		$.post($host+'php/process.php?action=logout', function(response, status, xhr){
			$('#msg').alert('<p>Logout successful, you will be redirected now.</p>', 'success', false);
			setTimeout(function(){document.location = '../admin/'},2000);
		});
		return false;
	});
	
    $("#login_form").submit(function() {
		$(this).find('input').each(function(){
			$(this).css('border', '1px solid #7F94BC');
			if ($(this).val() == '') {
				$(this).css('border', '1px solid red');
				$(this).focus();
            	return false;
			}
		});
		
		var data = $(this).serialize();
		$.getJSON($host+'php/process.php?action=login&ajax=1&noauth=1&jsoncallback=?', {username: $('#username').val(), password: $('#password').val()}, function(response){
            $msgs = '';
            $.each(response.messages, function(i, $message){
                $msgs += $message + '<br />';
            });
            $('#msg').alert($msgs, (!response.success ? 'error' : 'success'), false);
            success = response.success;
            if (response.success) {
                setTimeout(function(){
                    document.location = $host + 'admin/manager.php'
                }, 2000);
            } else {
				$('#msg').alert('A problem occured while connecting to the server.', 'error', false);
			}
        });
        return false;
    });
})(jQuery);

function resetLanding(){
	$('#tobehidden').hide();
	if (!$('#results').is(':visible')) {
		$('#searchcontainer').after('<div id="results"><p id="result_message"></p><div id="lvw-results"></div><div id="sponsored-results"><div id="mcs-results"></div><div id="scotchprint-results"></div></div></div>');
	} else {
		$('#lvw-results').hide();
		$('#sponsored-results').hide();
	}
	$('#result_message').html('<img style="position:relative;top:150px;margin-left:290px;" src="'+$host+'images/loading.gif" alt="loading" />');
}

