// Copyright 2007-2008 Gilt Groupe, Inc.

var gg;
if (!gg) {
    gg = {};
}


if (!gg.Admin) {
    gg.Admin = { _isAdmin: false };
}

gg.Admin.setIsAdminPage = function(isAdmin) {
    gg.Admin._isAdmin = isAdmin;
};

gg.Admin.isAdminPage = function() {
    return gg.Admin._isAdmin;
};

if (!gg.BeaconService) {
    gg.BeaconService = {};
}

// Parses the ifs parameter to extract out the given parameter
gg.BeaconService.get_ifs_param = function(paramName) {
    var ifs = jQuery.url.param("ifs");
    if (ifs == null || ifs == "") {
	return null;
    }
    var data = JSON.parse(unescape(ifs));
    if (data != null && data.bd != null) {
	return data.bd[paramName];
    }
    return null;
};

if (!gg.Site) {
    gg.Site = {};
}
gg.Site.currentSubsite = {};

// Prevents a function from executing again if it has already executed within a threshold
// Use 'id' to keep functions which should be throttled from stepping on each other.
gg._functionThrottle = {};
gg.throttleFunction = function(id, func, threshold) {
    return function(event) {
        var now = new Date().getTime();
        var last = gg._functionThrottle[id];
        if (!last || now > last + (threshold || 100)) {
            gg._functionThrottle[id] = now;
            return (func)(event);
        }
        if (event) {
            event.preventDefault();
        }
        return false;
    };
};

gg._formThrottle = {};
gg.throttleFormSubmit = function() {
    for (var i = 0, len = document.forms.length; i < len; ++i) {
        var form = document.forms[i];
        var id = form.id || ('form_' + Math.floor(Math.random()*1000000));
        if (gg._formThrottle[id]) {
            // don't install it twice on the same form -- might happen with ajax updates.
            return;
        }
        gg._formThrottle[id] = 1;
        jQuery(form).bind('submit', function(event) {
            var now = new Date().getTime();
            var last = gg._formThrottle[id] || 1;
            if (now > last + 1000) {
                gg._formThrottle[id] = now;
                // let event go ahead.
            }
            else {
                event.preventDefault();
                return false;
            }
            return true;
        });
    }
};

gg.cookieUpdate = {};

gg.cookieUpdate.updateCACookie = function() {
    if (!fl.Util.readCookie('ca_expiration')) {
        $.get('/ajax/update_ca_cookie', null, function(data) {
            if ('0' != data) {
                // Cookies have been updated. check if we can
                // redirect, but be very conservative. We only
                // care to redirect the /sale urls - if there are
                // no query parameters, we redirect
                var url = window.location.toString();
                if (-1 == url.indexOf('?') && -1 != url.indexOf('/sale')) {
                    window.location = url + '?ucac=1';
                }
            }
        }, 'text');
    }
};


if (!gg.FixIE) {
    gg.FixIE = {};
}

gg.FixIE.PngToGif = function() { // Deprecated
    var trans_png_exp = /\-trans.png/i;
    $('.trans').each(function(_,e) {
        if (e.src && trans_png_exp.test(e.src)) {
            e.src = e.src.replace(/\.png/,'.gif');
        }
    });
};

gg.FixIE.Sprites = function() {
  $("a.sprite, button.sprite").each(function() {
    var sizingClone = $(this).clone();
    sizingClone.appendTo("body");
    $(this).css({ width: sizingClone.width() });
    sizingClone.remove();
  }).filter("a.sprite-scalable")
      .hover(function(){
        if ($(this).hasClass("sprite-scalable-nodownstate")) {
          $(this).addClass("sprite-scalable-nodownstate-hover");
        } else {
          $(this).addClass("sprite-scalable-hover");
        }
      }, function() {
        $(this)
          .removeClass("sprite-scalable-nodownstate-hover")
          .removeClass("sprite-scalable-hover");
      })
      .mousedown(function() {
        if ($(this).hasClass("sprite-scalable-nodownstate")) {
          $(this).addClass("sprite-scalable-nodownstate-active");
        } else {
          $(this).addClass("sprite-scalable-active");
        }
      })
      .mouseup(function() {
        $(this)
          .removeClass("sprite-scalable-nodownstate-active")
          .removeClass("sprite-scalable-active");
      });
};

if (!gg.FlashMessage) {
    gg.FlashMessage = {};
}

gg.FlashMessage.init = function () {
    log.setup("startup", "gg")("Initializing Flash Message");
    var flash_cookie = fl.Util.readCookie('flash');
    log("Flash Cookie:", flash_cookie);
    if (flash_cookie) {
        var flash_message = gg.parse_json(flash_cookie);
        fl.Util.expireCookie('flash');
        if (flash_message.notice) {
            var flash_message_div = $('#flash_message');
            if (flash_message_div) {
                flash_message_div.append(flash_message.notice);
                flash_message_div.show();
            }
        }
    }
};

if (!gg.Sprite) {
    gg.Sprite = {};
}

gg.Sprite.init = function() {
    log.setup("startup", "gg", "sprite")("Initializing Sprites");
    var sprites = $('a[sprite_offset], input[sprite_offset]');
    var i = sprites.length;
    while (i--) {
        gg.Sprite.enableSprite(sprites.eq(i));
    }
};

gg.Sprite.enableSprite = function(sprite) {
    if (fl.Util.isInitialized('Sprite', sprite)) {
        return;
    }
    log.setup("startup", "gg", "sprite")("Enabling Sprite #%o", sprite);
    sprite.html('');
    var offset = sprite.attr('sprite_offset');
    sprite.hover(
        function() {
            log.setup("interaction", "gg", "sprite")("Sprite #%o move %dpx", sprite, offset);
            sprite.css({ backgroundPosition: '0 -' + offset + 'px' });
        },
        function() {
            log.setup("interaction", "gg", "sprite")("Sprite #%o reset", sprite);
            sprite.css({ backgroundPosition: '0 0' });
        }
    );
};

if (!gg.Tracking) {
    gg.Tracking = {};
}
if (!gg.Tracking.Google) {
    gg.Tracking.Google = {};
}

gg.Tracking.Google.Init = function () { // Why set constant data in a function?
    gg.Tracking.Google.config = {
        vendor_id: 'K187348'
    };
};

gg.Tracking.Google.setActionTag = function() {
    var data = fl.Util.readCookie('blackbird_user_data');
    var hash = "";
    if (data) {
        hash = data.split('_')[0];
    }
    var img_tag = $.format('<img width="1" height="1" src="https://clickserve.cc-dt.com/link/action?oid=ccdt_{0}&amp;vid={1}" id="ga_action_tag" alt="" style="display: none;"/>', hash, gg.Tracking.Google.config.vendor_id);
    $("#footer").append(img_tag);
};

if (!gg.Tracking.Google.AdWords) {
    gg.Tracking.Google.AdWords = {};
    if(document.location.protocol.toString().toLowerCase()=="https:") {
      gg.Tracking.Google.AdWords.script = 'https://www.googleadservices.com/pagead/conversion.js';
    } else {
      gg.Tracking.Google.AdWords.script = 'http://www.googleadservices.com/pagead/conversion.js';
    }
}

if (!gg.Validation) {
    gg.Validation = {};
}

gg.Validation.disable = function() {
   /* var el = $('#user_first_name');
    el.unbind('blur', el.data("validate_required"));*/
};

gg.Validation.enable = function() {
    /*var el = $('#user_first_name');
    el.data("validate_required", function() {
        fl.Validate.Required(el);
    });
    el.blur(el.data("validate_required"));*/
};

// Add authentication token to certain links (like iCal and RSS links).
// To add the user's login key to any link just add the 'lk' class to it.
gg.processLoginKey = function() {
    log.setup("startup", "gg")("Appending login key to links");
    var data = gg.Usermeta.data();
    var login_key = null;

    if (data && data.login_key) {
        login_key = data.login_key;
    }

    var keys = $ ('.lk');
    var i = keys.length;
    while (i--) {
        var el = keys.eq(i);
        if (el.attr('href')) {
            if (!login_key) {
                el.attr("href", '/ajax/update_usermeta_cookie/?return_url=' + encodeURIComponent(el.attr("href")));
            } else {
                log("Appending login key to %s", el.attr("href"));
                if (-1 == el.attr("href").indexOf('?')) {
                    el.attr("href", el.attr("href") + '?k=' + login_key);
                } else {
                    el.attr("href", el.attr("href") + '&k=' + login_key);
                }
            }
        }
    }
};

gg.site_feedback_set_loading = function(id) {
    $("#" + id).html('<div id="MB_loading">Submitting Feedback...</div>');
};

gg.to_json = function(value) {
    return JSON.stringify(value);
};

gg.parse_json = function(value) {
    if (!value) {
        return null;
    }
    if ("object" == typeof value) {
        return value;
    }
    // hack to unescape spaces...unescape and unescapeURI only handle %20 and JSON.parse doesn't do it
    value = value.replace(gg.parse_json.strip, ' ');
    return JSON.parse(value);
};
gg.parse_json.strip = /[\+\n\r]/g;

gg.random_string = function(string_length, hex_only) {
    var randomstring = '';
    var i = string_length;
    while (i--) {
        if (!hex_only) {
            var ccode = Math.floor(Math.random() * 62) + 48; // 0-9
            if (57 < ccode) {                                // A-Z
                ccode += 7;
            }
            if (90 < ccode) {                                // a-z
                ccode += 6;
            }
        } else {
            ccode = Math.floor(Math.random() * 16) + 48; // 0-9
            if (57 < ccode) {
                ccode += 39;                             // a-f
            }
        }
        randomstring += String.fromCharCode(ccode);
    }
    return randomstring;
};

if (!gg.History) {
  gg.History = {};
}

gg.History.back = function(url) {
  if (history.length > 1) {
    history.back();
  } else if (url != null) {
    window.location = url;
  }
};
