﻿function Cookie(str)
{
    var match = str.match(/^ *(\w+)=(.+)$/);
    var name = match[1];
    var text = match[2];
    match = text.match(/(\w+)=([^&]+)/);
    var values = {};
    
    var rx = /(\w+)=([^&]+)/g;
    match = rx.exec(text);
    while (match != null) 
    {
        values[match[1]] = match[2];
        match = rx.exec(text);
    }
    
    this.getName = function() { return name;  }
    this.getText = function() { return text; }
    this.setText = function(newText) { this.clear(); text = newText;}
    this.getValue = function(key) { return values[key]; }        
    this.setValue = function(key,value) { values[key] = value; }
    this.clear = function()
    {
        for(key in values)
            delete values[key];
    }
    this.hasKeys = function()
    {
        for(key in values)
            return true;
        return false;
    }
    this.save = function(days)
    {
        var temp = name+'=';
        if (this.hasKeys())
        {
            var first = true;
            for(key in values)
            {
                if (!first)
                    temp += '&';  
                else
                    first = false;                     
                temp+=key+'='+values[key];                        
            }
        }
        else
            temp += text;
        
        if (days)
        {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            temp += "; expires="+date.toGMTString();
        }
        document.cookie = temp + '; path=/';
    } 
    this.erase = function()
    {
        document.cookie = this.getName() + '=; expires=-1; path=/';
    }       
}
Cookie.find = function(name)
{
    var arr = document.cookie.split(';');
    for(var i = 0; i < arr.length; i++)
    {
        var c = new Cookie(arr[i]);
        if (c.getName() == name)
            return c;
    }
    return null;
}

var email;
var cookie;
function subscribe(cookieName)
{
    email = document.getElementById('tbEmail').value;
    var match = email.match(/^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i);
    if (match == null)
    {
        alert('Invalid email, please try again');
        return;
    }
    cookie = Cookie.find(cookieName);
    var zip = cookie.getValue('zip');
    if (!zip) zip = null;
    
    Products.Subscribe(cookie.getValue('id'), email, zip, subscribeSuccess, subscribeError, cookieName);
}
function subscribeSuccess()
{
    cookie.setValue('email', email);
    cookie.save(720);
    var box = document.getElementById('emailDiv');
    box.innerHTML = '';
    var p = document.createElement('P');
    p.innerHTML = 'Thank you for subscribing to the YourDeal Newsletter';
    box.appendChild(p);
}
function subscribeError(ex)
{
    alert('Error !\n' + ex.get_message());
}
