/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * https://www.opensource.org/licenses/mit-license.php
 * https://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in SECONDS or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$.fn.defaultValueCleaner = function() {
	
	this.each(function(){
		$(this).attr('default',this.value);
				
		$(this).bind('focus',function(){ 
			if (this.value == $(this).attr('default')) {
				this.value = '';
				$(this).addClass('valueSet');
			}
		});
		$(this).bind('blur', function(){ 
			if (this.value == '') { 
				this.value = $(this).attr('default'); 
				$(this).removeClass('valueSet');
			} 
		});
	});
	
};

$.fn.tabs = function() {
	
	this.each(function(){
		$(this).bind('click', function(){
			$('div.tab').css({display:'none'});
			$($(this).attr('href')).css({display:'block'});
			$('#tabs li').removeClass('act');
			$(this).parents('li').addClass('act');
			this.blur();
			return false;
		});
	});
	
};

$.fn.slider = function() {
	
	this.each(function(){
			$(this).bind('click', function(){
			if (!$($(this).attr('href')).hasClass('shown')){	
				$(this).parents('dl').find('dd.shown').slideUp('fast').removeClass('shown');
				$($(this).attr('href')).slideDown('fast').addClass('shown'); 
			} else {
				$(this).parents('dl').find('dd.shown').slideUp('fast').removeClass('shown');
			}
			return false;
		});
	});
	
};

var cFrm = {
	
	root: null,
	init: function(root) {
		cFrm.root = root;
		c = $.cookie('cFrmFinishedOk');
		if (c == 1) {
			cFrm.showInstantOk();	
		}
		$('#frmSubmit').bind('click', function(){
			cFrm.showLoader(cFrm.submit);			
			return false;
		});
		$('#frmErrorBack').bind('click',function(){
			cFrm.root.find('.loader, .result.ok').css({display:'none'});
			$('#formBoxInner').animate({left: '-28px'},235);
			return false;	
		});
		$('#frmName, #frmLastname, #frmEmail, #frmPhone').bind('keydown', function(){ $(this).removeClass('err'); });
		$('#frmAccept').bind('change', function(){ $('#frmAcceptInfo').removeClass('err'); });
	},
	submit: function() {
		var err = false;
		if (!$('#frmName').val()) {
			err = true;
			$('#frmName').addClass('err');
		}
		if (!$('#frmLastname').val()) {
			err = true;
			$('#frmLastname').addClass('err');
		}
		if (!$('#frmEmail').val()) {
			err = true;
			$('#frmEmail').addClass('err');
		}
		else
		{
			 var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   		 if(reg.test($('#frmEmail').val()) == false) {
   		 	 err = true;
				 $('#frmEmail').addClass('err');
			 }
		}
		
		if (!$('#frmPhone').val()) {
			err = true;
			$('#frmPhone').addClass('err');
		}
		if (!$('#frmAccept').is(':checked')) {
			err = true;
			$('#frmAcceptInfo').addClass('err');
		}
		
		if (err) {
			setTimeout(cFrm.showError, 500);
			return;
		}
		/// wysyłka
		//setTimeout(cFrm.showOk, 500);
		$.ajax({
		      url: "/subscribe.php",
		      type: "POST",
		      data: cFrm.root.find('form').serialize(),
		      dataType: "json",
		      success: cFrm.ajaxSuccess
		   }
		);
	},
	ajaxSuccess: function(d)
	{
		  if (d.status == 'ok') {
		  		if (d.msg != '') {	
					$('#resultOkStatusText').html(d.msg);
		  		}
		  		if (d.tb != '') {
					cFrm.root.find('.result.ok').append('<img src="'+d.tb+'" alt="" style="border: none" />');
		  		}
		  		cFrm.showOk();
		  		$.cookie('cFrmFinishedOk', '1', { expires: 600, path: '/' });
		  		return;
		  }
		  
		  if (d.status == 'err') {
		  	  	if (d.msg != '') {
					var fields = d.msg.split(',');
		  			for (var f in fields) {
						$('#'+fields[f]).addClass('err');
		  			}
		  		}
		  		cFrm.showError();
		  		return;
		  } 
		  
	},
	
	showLoader: function(callback) {
		cFrm.root.find('.loader').css({display:'block'});
		cFrm.root.find('#formBoxInner').animate({left: '-270px'},235,callback);
	},
	showError: function() 
	{
		cFrm.root.find('.result.ok').css({display:'none'});
		cFrm.root.find('#formBoxInner').animate({left: '-512px'},235);
	},
	showOk: function()
	{
		cFrm.root.find('.result.ok').css({display:'block'});
		cFrm.root.find('#formBoxInner').animate({left: '-512px'},235);
	},
	showInstantOk: function()
	{
		cFrm.root.find('.result.ok').css({display:'block'});
		cFrm.root.find('#formBoxInner').css({left: '-512px'});	
	}
};

$(document).ready(function(){
	$('#newsletterEmailInput').defaultValueCleaner();
	$('.ttab').tabs();
	$('.tab7 dt a').slider();	
	$('#tab2Shortcut').bind('click', function(){ $('#tab2Trigger').trigger('click'); return false; });
	cFrm.init($('#formBox'));
});

/*
var flashvars = { 
	cyfra_1: "1",
	cyfra_2: "2",
	cyfra_3: "2",
	stopka: "* Stopa+zwrotu+Investor+FIZ+od+02.09.05+do+31.07.10",
	okres: "59"
};

swfobject.embedSWF("https://gold.investors.pl/gold_counter.swf", "counter", "150", "150", "9", "expressInstall.swf", flashvars);

*/
